簡體   English   中英

刪除包含txt文件python中特定元素的行

[英]Remove line that contain specific element in a txt file python

我有一個包含元素的 txt 文件:

705.95 117.81 1242.00 252.43 5.02

1036.12 183.52 1242.00 375.00 1.96

124.11 143.43 296.91 230.32 10.70

0.00 0.00 0.00 0.00 4.84

0.00 6.60 112.99 375.00 17.50

0.00 186.66 14.82 375.00 8.23

695.36 162.75 820.66 263.08 12.84

167.61 134.45 417.75 222.10 27.61

0.00 0.00 0.00 0.00 6.86

0.00 0.00 0.00 0.00 11.76

我想刪除包含 0.00 0.00 0.00 0.00 作為每行前四個元素的行,我該如何使用 python 來做到這一點? 非常感謝您的幫助。

with open('file.txt', 'r') as infile:
  with open('output.txt', 'w') as outfile:
    for line in infile:
      if not line.startswith('0.00 0.00 0.00 0.00'):
        outfile.write(line)

在這里,我們用您的行打開 file.txt 進行讀取,並打開 output.txt 以寫入結果。 然后,我們遍歷輸入文件的每一行,如果它不是以 '0.00 0.00 0.00 0.00' 開頭,則將其寫入結果文件中。

如果你想覆蓋文件而不創建新的輸出文件,你可以試試這個。 以下代碼還可以幫助您遍歷當前目錄中的所有文本文件。

import glob

for i in glob.glob("*.txt"):
    with open(i, "r+") as f:
        content = f.readlines()

        f.truncate(0)
        f.seek(0)

        for line in content:
            if not line.startswith("0.00 0.00 0.00 0.00"):
                f.write(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM