簡體   English   中英

如何從txt文件中刪除特定行和以下n行?

[英]How to delete a specific line and the following n lines from a txt file?

我正在創建一個程序來更新一個包含城市列表的文本文件:

New York City
New York
USA

Newark
New Jersey
USA

Toronto
Ontario
Canada

如果我想使用 bash 腳本刪除紐瓦克的詳細信息,我可以這樣做:

sed -i "/Newark/,+3d" test.txt

這會給我留下以下內容:

New York City
New York
USA

Toronto
Ontario
Canada

但是,我想在 Python 中執行此操作,並且在與 Newark 的行之后,我在弄清楚如何刪除以下行時遇到了問題。 我可以刪除紐瓦克:

with open('test.txt') as oldfile, open('test2.txt', 'w') as newfile:
        for line in oldfile:
            if not "Newark" in line:
                newfile.write(line)

os.remove('test.txt')
os.rename('test2.txt', 'test.txt')

但這對其余兩行沒有任何作用,並創建了一個新文件,然后我必須使用它來替換原始文件。

  1. 如何使用 Python 模擬 sed 命令的功能?
  2. 有什么方法可以進行文件內編輯,因此每次需要刪除文件時都不必創建和替換文件?

有櫃台嗎? 這里是:

with open('test.txt') as oldfile, open('test2.txt', 'w') as newfile:
    skip = 0
    for line in oldfile:
        if "Newark" in line:
            skip = 3
        elif skip > 0:
            skip = skip - 1
        else:
            newfile.write(line)

編輯:

我只回答了第一個問題。 fileinput支持文件編輯,請看這里: 如何搜索和替換文件中的文本? 順便說一句,我也建議就地,因為它不會劫持標准輸出

您可以使用fileinput模塊就地編輯文件:

import fileinput
import itertools

skip = 3
with fileinput.input("test.txt", inplace=True) as f:
     for line in f:
         if "Newark" not in line:
             # stdout is redirected to the file
             sys.stdout.write(line)
         else:
             # Skip lines
             next(itertools.islice(f, skip, skip), None)

暫無
暫無

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

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