如何从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
如果我想使用bash脚本删除Newark的详细信息,可以执行以下操作:
If I wanted to delete the details for Newark using a bash script, I can do this:
sed -i "/Newark/,+3d" test.txt
这会让我留下以下内容:
And that would leave me with the following:
New York City
New York
USA
Toronto
Ontario
Canada
但是,我想在Python中执行此操作,在Newark之后,我在解决如何删除以下行时遇到了问题.我可以删除纽瓦克:
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. 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.
- 如何使用Python模仿sed命令的功能?
- 有什么方法可以进行文件内编辑,因此我不必每次都需要从文件中删除文件时创建并替换文件吗?
推荐答案
带有计数器?在这里:
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)
我只回答了第一个问题.文件输入支持文件编辑,请在此处查看:就地,因为
I only answered the first question. fileinput support file editing, please have a look here: How to search and replace text in a file? Btw, I would recommend also in-place because it doesn't hijack stdout
这篇关于如何从txt文件中删除特定行和以下n行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!