简体   繁体   English

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

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

I'm creating a program to update a text file, that has a list of cities:我正在创建一个程序来更新一个包含城市列表的文本文件:

New York City
New York
USA

Newark
New Jersey
USA

Toronto
Ontario
Canada

If I wanted to delete the details for Newark using a bash script, I can do this:如果我想使用 bash 脚本删除纽瓦克的详细信息,我可以这样做:

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

And that would leave me with the following:这会给我留下以下内容:

New York City
New York
USA

Toronto
Ontario
Canada

However, I would like to do this in Python, and I'm having issues figuring out how to delete the following lines, after the line with Newark.但是,我想在 Python 中执行此操作,并且在与 Newark 的行之后,我在弄清楚如何删除以下行时遇到了问题。 I can delete 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')

But this does nothing for the remaining two lines, and creates a new file I then have to use to replace the original file.但这对其余两行没有任何作用,并创建了一个新文件,然后我必须使用它来替换原始文件。

  1. How can I go about mimicing the sed command's functionality with Python?如何使用 Python 模拟 sed 命令的功能?
  2. Is there any way to do an in file edit, so I do not have to create and replace the file everytime I need to delete from it?有什么方法可以进行文件内编辑,因此每次需要删除文件时都不必创建和替换文件?

With a counter ?有柜台吗? Here it is:这里是:

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)

Edit:编辑:

I only answered the first question.我只回答了第一个问题。 fileinput support file editing, please have a look here: How to search and replace text in a file? fileinput支持文件编辑,请看这里: 如何搜索和替换文件中的文本? Btw, I would recommend also in-place because it doesn't hijack stdout顺便说一句,我也建议就地,因为它不会劫持标准输出

You can use the fileinput module to edit files in place:您可以使用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