我想找到以列表中的单词开头的行。如果找到了该词,我希望它所在的行和前一行被删除。 我能够得到该行和previos并打印它们,但是我无法避免不将它们传递给我的输出文件。 F.e。:
输入:
This is not supposed to be deleted.
This shall be deleted.
Titel
This is not supposed to be deleted.
This is not supposed to be deleted
输出:
This is not supposed to be deleted.
This is not supposed to be deleted.
This is not supposed to be deleted
我使用此代码进行了尝试,但是我不断收到TypeError:'str'对象不支持项目分配
with open(file1) as f_in, open(file2, 'w') as f_out:
lines = f_in.read().splitlines()
for i, line in enumerate(lines):
clean = True
if line.startswith(('Text', 'Titel')):
for (line[i-1]) in lines:
clean = False
for line in lines:
clean =False
if clean == True:
f_out.write(line)
答案 0 :(得分:2)
您不必一次读取文件。相互读取各行,并存储当前行,但仅在下次读取后才将其写出。
with open("file1") as finp, open("file2","w") as fout:
lprev=""
for line in finp:
if line.startswith("Titel") or line.startswith("Text"):
lprev=""
continue
if lprev:
fout.write(lprev)
lprev=line
if lprev:
fout.write(lprev) # write out the last line if needed
答案 1 :(得分:1)
首先跟踪要复制的行:
lines_to_keep = []
with open(file1) as f_in:
deleted_previous_line = True
for line in f_in:
if line.startswith(('Text', 'Titel')):
if not deleted_previous_line:
del lines_to_keep[-1]
deleted_previous_line = True
continue
deleted_previous_line = False
lines_to_keep.append(line)
如果连续的行以“文本”或“标题”开头,则使用deleted_previous_line
的技巧是必要的,以确保它不会删除过多的行。
然后将其写入您的输出文件
with open(file2, 'w') as f_out:
f_out.writelines(lines_to_keep)