如何使用python中的行号从文本文件中删除行
问题内容:
这是一个示例文本文件
the bird flew
the dog barked
the cat meowed
这是我的代码来查找我要删除的短语的行号
phrase = 'the dog barked'
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if phrase in line:
print 'found at line:', num
我可以为此添加些什么,以便删除我尝试过的行号(数字)
lines = myFile.readlines()
del line[num]
但这不起作用,我应该如何处理呢?
问题答案:
您可以使用该fileinput
模块来更新文件-请注意,这将删除 所有 包含短语的行:
import fileinput
for line in fileinput.input(filename, inplace=True):
if phrase in line:
continue
print(line, end='')