繁体   English   中英

将特定行从一个文件写入另一文件

[英]writing specific lines from one file to another file

我正在尝试读取文件,查找一个特定的单词,如果一行包含该单词,请删除该行并将其余的行发送到新文件。 这就是我所拥有的,但是它只是找到其中的一条线,而不是全部。

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:您基本上用下一行覆盖了文件的全部内容 无论是打开追加模式的文件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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM