我有一个时序数据文件,有时会在某些字段中生成“ 0.00”值。我想编写一个脚本来检查文件并删除所有包含“ 0.00”值的行。我设法读取文件,删除行并保存在其他文件中。 但是,我需要覆盖原始文件。这是因为另一个软件包正在使用该特定文件,在该文件中我无法使用这些“ 0.00”值。
这就是我得到的:
def remove_line(line, stop):
return any([word in line for word in stop])
stop = ["0.00"]
with open("7290_0.dat", "r") as f, open("7290_1.dat", "w") as w:
for line in f:
if not remove_line(line, stop):
w.write(line)
预先感谢您的建议。
答案 0 :(得分:0)
只需读取行并将必要的行再次写入同一文件即可。
stop = "0.00"
with open("7290_0.dat", "r") as f:
lines = f.readlines()
with open("7290_0.dat", "w") as f:
for line in lines:
if stop not in line:
f.write(line)
如果缓冲区有限,还可以执行以下操作:
stop = "0.00"
lines = []
with open("7290_0.dat", "r") as f:
line = f.readline()
if not line:
break
if stop not in line:
lines.append(line)
with open("7290_0.dat", "w") as f:
for line in lines:
f.write(line)
答案 1 :(得分:0)
一种经过验证的,安全的,经过测试的解决方案是像以前一样写入新文件,然后用新文件替换原始文件(使用os.rename()
)。
这避免了将整个文件加载到内存中,避免了很多潜在的其他问题(竞争条件等),并确保您在重命名操作之前不会崩溃的情况下不会丢失数据。
编辑:如Michael Butscher所述,在Windows上,您可能需要先删除原始文件(使用os.remove()
),然后再进行os.rename()
。
答案 2 :(得分:-1)
您可以尝试以下
stop = "0.00"
with open("7290_0.dat", "r+") as f:
data = f.readlines()
f.seek(0)
for line in data:
if stop not in line:
f.write(line)