我有一个应用程序从文件中读取行,并在读取每行时运行其魔法.一旦读取并正确处理了该行,我想从文件中删除该行.已保留已删除行的备份.我想做点什么
file = open('myfile.txt', 'rw+')
for line in file:
processLine(line)
file.truncate(line)
Run Code Online (Sandbox Code Playgroud)
这似乎是一个简单的问题,但我想做的不错,而不是一大堆复杂的seek()和tell()调用.
也许我真正想做的就是从文件中删除一个特定的行.
在花了很长时间来解决这个问题后,我认为每个人都可能是对的,这不是一个好办法.它似乎是如此优雅的解决方案.我正在寻找的东西类似于FIFO,它只会让我从文件中弹出行.
jfs*_*jfs 18
with open('myfile.txt', 'r+') as file:
for line in file:
processLine(line)
file.truncate(0)
Run Code Online (Sandbox Code Playgroud)
lines = open('myfile.txt').readlines()
for line in lines[::-1]: # process lines in reverse order
processLine(line)
del lines[-1] # remove the [last] line
open('myfile.txt', 'w').writelines(lines)
Run Code Online (Sandbox Code Playgroud)
import fileinput
for line in fileinput.input(['myfile.txt'], inplace=1):
try: processLine(line)
except Exception:
sys.stdout.write(line) # it prints to 'myfile.txt'
Run Code Online (Sandbox Code Playgroud)
一般来说,正如其他人已经说过你想要做的事情一个坏主意.
你不能.在当前文件系统上实际的文本文件实现是不可能的.
文本文件是顺序的,因为文本文件中的行可以是任意长度.删除特定行意味着从该点重写整个文件.
假设您有一个包含以下3行的文件;
'line1\nline2reallybig\nline3\nlast line'
Run Code Online (Sandbox Code Playgroud)
要删除第二行,您必须移动磁盘中的第三行和第四行的位置.唯一的方法是将第三行和第四行存储在某处,截断第二行的文件,然后重写缺失的行.
如果你知道文本文件中每一行的大小,你可以在任何位置使用截断文件,.truncate(line_size * line_number)但即使这样你也必须在行之后重写所有内容.
你最好保留一个索引到文件中,这样你就可以从最后停止的地方开始,而不会破坏文件的一部分.像这样的东西会起作用:
try :
for index, line in enumerate(file) :
processLine(line)
except :
# Failed, start from this line number next time.
print(index)
raise
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17851 次 |
| 最近记录: |