我正在创建一个程序来更新文本文件,该文件具有城市列表:
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')
但是这对其余两行没有任何作用,并创建一个新文件,然后我必须使用它来替换原始文件。
带柜台?这是:
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)