-2

我想找到以列表中的单词开头的行。如果找到这个词,我希望它所在的行和前一行被删除。我能够得到该行和上一个并打印它们,但我无法将它们传递给我的输出文件。铁:

输入:

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' object does not support item assignment

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)
4

2 回答 2

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
于 2018-11-13T16:19:20.410 回答
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)
于 2018-11-13T15:40:37.637 回答