[英]writing specific lines from one file to another file
I'm trying to read a file, look for a specific word and if a line contains that word, remove the line and send the remaining lines to a new file. 我正在尝试读取文件,查找一个特定的单词,如果一行包含该单词,请删除该行并将其余的行发送到新文件。 Here's what I have but it is only finding one of the lines not all of them;
这就是我所拥有的,但是它只是找到其中的一条线,而不是全部。
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)
The problem is that when you do with open('fixed.txt', 'w') as f:
you basically overwrite the entire content of the file with that one next line. 问题是,当您将
with open('fixed.txt', 'w') as f:
您基本上用下一行覆盖了文件的全部内容 。 Either open the file in append mode a
... 无论是打开追加模式的文件
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)
... or (probably better) open the file in w
mode, but just once at the beginning: ...或(可能更好)以
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.