gpt4 book ai didi

Python确保文件以行返回结尾?

转载 作者:行者123 更新时间:2023-11-28 18:36:29 25 4
gpt4 key购买 nike

我想要一个接受文件路径的函数,检查文件是否以 \n 结尾,如果有则添加 \n它没有。

我知道我可以通过打开文件两次来做到这一点,一次是读取模式,然后是附加模式,但我觉得我一定遗漏了一些东西......我觉得 'w+'模式,例如,必须能够做到这一点。

这是一种打开文件两次的方法(我想要一些更简单的东西,你只打开它一次)。

def ensureFileEndsWith(path, end):
with open(path) as f:
f.seek(-1, 2)
alreadyGood = f.read(1) == end
if not alreadyGood:
with open(path, 'a') as f:
f.write(end)

我想做同样的事情,但只打开文件一次。我试过这个:

def ensureFileEndsWith(path, end):
with open(path, 'w+') as f:
f.seek(-1, 2)
if not f.read(1) == end:
f.write(end)

但是它打印出了这个异常:

IOError: [Errno 22] Invalid argument

关于我在以 'w+' 模式打开的文件中使用 seek

最佳答案

首先你要open(path, 'r+'); 'w+' 截断文件。您收到该错误的原因是因为您不能对空文件执行 f.seek(-1, 2) 操作。这应该为你做:

def ensureFileEndsWith(path, end):
with open(path, 'r+') as f:
try:
f.seek(-len(end), 2)
except IOError:
# The file is shorter than end (possibly empty)
f.seek(0, 2)

# Passing in a number to f.read() is unnecessary
if f.read() != end:
f.write(end)

关于Python确保文件以行返回结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32027396/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com