如何从Python的txt文件中删除特定行和以下n行

问题描述 投票:1回答:1

我正在创建一个程序来更新文本文件,该文件具有城市列表:

New York City
New York
USA

Newark
New Jersey
USA

Toronto
Ontario
Canada

如果我想使用bash脚本删除Newark的详细信息,则可以执行此操作:

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

这会让我留下以下内容:

New York City
New York
USA

Toronto
Ontario
Canada

但是,我想用Python做到这一点,在Newark行之后,在解决如何删除以下行时遇到了问题。我可以删除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. 是否有任何方法可以进行文件内编辑,所以不必每次都需要从文件中删除文件时创建和替换文件?
python sed text-files edit
1个回答
0
投票

带柜台?这是:

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)
© www.soinside.com 2019 - 2024. All rights reserved.