【问题标题】:How to delete a specific line and the following n lines from a txt file?如何从 txt 文件中删除特定行和以下 n 行?
【发布时间】:2020-03-30 19:22:45
【问题描述】:

我正在创建一个程序来更新一个包含城市列表的文本文件:

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 行之后删除以下行时遇到问题。我可以删除纽瓦克:

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】:

    有柜台吗?这里是:

    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支持文件编辑,请看这里:How to search and replace text in a file? 顺便说一句,我也推荐in-place,因为it doesn't hijack stdout

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2019-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-21
        • 1970-01-01
        • 2018-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多