簡體   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