我正在创建一个程序来更新文本文件,该文件具有城市列表:
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')
但这对其余两行无效,并创建了一个新文件,我不得不用它来替换原始文件。
答案 0 :(得分:3)
有柜台吗?在这里:
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
答案 1 :(得分:0)
您可以使用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)