Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将特定行从一个文件写入另一个文件_Python_Python 3.x_File Io - Fatal编程技术网

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

Python 将特定行从一个文件写入另一个文件,python,python-3.x,file-io,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('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)

问题是,当您使用open('fixed.txt',w')作为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)

请标记语言