如何从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 support file editing, please have a look here: How to search and replace text in a file? 顺便说一句,我也推荐 in-place because it doesn't hijack stdout

您可以使用 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)