如何通过将它与变量进行比较来删除最后一行

时间:2016-04-18 00:07:48

标签: python-3.x

如果我有包含更新行的文本文档

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) 

1 个答案:

答案 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()