Python - 删除行和前面的行(匹配模式模式)

Python - deleting lines and previos lines (matching pattern patterns)

我想找到以列表中的单词开头的行。如果找到这个词,我希望它所在的行和上一行被删除。 我能够得到行和 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

我用这段代码试过了,但我一直收到类型错误:'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)

首先记下要复制的行:

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)

如果连续行以 'Text' 或 'Titel'.

开头,deleted_previous_line 的技巧是必要的,以确保它不会删除太多行

然后将其写入您的输出文件

with open(file2, 'w') as f_out:
    f_out.writelines(lines_to_keep)

您不必立即阅读文件。逐行读取,并存储当前行,但只有在下次读取后才写出,或者不写。

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