python - 将一个文件中的特定行写入另一个文件

标签 python python-3.x file-io

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

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/

相关文章:

java - 长期运行的统计过程 - 关于语言选择的想法?

python - django 错误(外部 IP)

python - python 3 中的 Expat 解析

algorithm - 提高以下算法的效率

python - 以视觉可读的方式将张量写入文件

python - 如何使用 pygtk 获取 gnome2 桌面上所有窗口的列表?

python - csvjoin 多列

python - Sublime Text 3 构建系统问题

C++ 打印时间只到一个文件!

c# - 如何从文件路径名中提取文件名?