我正在尝试读取文件,查找特定单词,如果某行包含该单词,则删除该行并将剩余行发送到新文件。 这是我所拥有的,但它只找到其中一行而不是全部;
with open('letter.txt') as l:
for lines in l:
if not lines.startswith("WOOF"):
with open('fixed.txt', 'w')as f:
print(lines.strip(), file=f)
最佳答案
问题是,当您执行 with open('fixed.txt', 'w') as f:
时,您基本上 overwrite the entire content of the file与下一行。以附加模式打开文件a
...
with open('letter.txt') as l:
for lines in l:
if not lines.startswith("WOOF"):
with open('fixed.txt', 'a') as f:
print(lines.strip(), file=f)
...或者(可能更好)以 w
模式打开文件,但仅在开头打开一次:
with open('letter.txt') as l, open('fixed.txt', 'w') as f:
for lines in l:
if not lines.startswith("WOOF"):
print(lines.strip(), file=f)
关于python - 将一个文件中的特定行写入另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25158438/