什么是撤销文件写入的最佳方法?如果我正在循环中逐行写入,并且想要撤销先前的写入并替换为其他内容,我该如何操作?有什么想法吗?
提前感谢!
提前感谢!
正如其他人所指出的,这并没有太多意义,最好在必要时再进行编写。在您的情况下,您可以将“写入指针”保持在处理的一行之后。
伪代码:
previousItem = INVALID
for each item I:
is I same as previousItem?
then update previousItem with I
else
write previousItem to file
previousItem = I
write previousItem to file
previousItem
是唯一保存在内存中的项目,并在需要时更新为“accumulate”。只有当下一个项目不“与之相同”时,才将其写入文件。fseek()
。起初,这似乎更简单易懂,但它是一个完全无法调试的噩梦。如前所述,最好不要尝试撤销写入操作。但如果你真的想这么做,也很容易:
import os
f = open("test.txt", "w+")
f.write("testing 1\n")
f.write("testing 2\n")
pos = f.tell()
f.write("testing 3\n")
f.seek(pos, os.SEEK_SET)
f.truncate(pos)
f.write("foo\n")
只需记录要倒带的文件位置,将其定位回去并截断文件到该位置即可。
这样做的主要问题是它无法在流上工作。您不能对stdout、管道或TCP流进行此操作,只能对真实文件执行此操作。
from itertools import islice
def seek_to_line(f, n):
for ignored_line in islice(f, n - 1):
pass # skip n-1 lines
f = open('foo')
seek_to_line(f, 9000) # seek to line 9000
# print lines 9000 and later
for line in f:
print line
to_write = ""
for item in alist:
#Check to make sure that I want to write
f.write(to_write)
to_write = ""
#Compute what you want to write.
to_write = something
#We're finished looping so write the last part out
f.write(to_write)