如果我有包含更新行的文本文档
line1
line2
line3
line4
我需要删除更新文本文档中的最后一行,但是每次在上一个块中更改时都会通过与变量键进行比较来删除它
key = 'line to remove'
with open('D:\path\doc.txt', 'w') as searchfile:
for line in searchfile:
if key in line:
searchfile.write(line)
答案 0 :(得分:0)
如果您想在打开单个文件时执行此操作:
f = open("D:\path\doc.txt","r+") # read the whole file
lines = f.readlines()
f.seek(0) # point to the beginning of the file
for i in lines:
if i != "line to remove":
f.write(i)
f.truncate()
f.close()