我正在尝试编写一些内容,我首先在txt文件中查找一行中的字符串,当找到它时,我想跳过该行和下面的行以获取没有这些行的新txt文件。我真的没有从其他问题得到任何解决方案,所以也许这将工作
我的代码现在看起来像这样:
with open("bla.txt", "r+") as f
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "abc" not in line:
f.write(line)
else:
pass
pass
f.truncate()
我用next(f)
尝试过,但它对我不起作用。提前谢谢
答案 0 :(得分:0)
如果当前行包含字符串ABC:
,此代码将创建一个跳过当前行和下一行的新文件with open('bla.txt','r') as f:
text = f.read()
lines = text.split('\n')
with open('new_file.txt','w') as nf:
l = 0
while l<(len(lines)):
if 'ABC' in lines[l]:
l = l+2
else:
nf.write(lines[l]+'\n')
l = l+1
答案 1 :(得分:0)
尝试这样简单的事情:
import os
search_for = 'abc'
with open('input.txt') as f, open('output.txt', 'w') as o:
for line in f:
if search_for in line:
next(f) # we need to skip the next line
# since we are already processing
# the line with the string
# in effect, it skips two lines
else:
o.write(line)
os.rename('output.txt', 'input.txt')