[英]Python - deleting lines and previos lines (matching pattern patterns)
I want to find the lines which start with a word of a list.我想找到以列表中的单词开头的行。 If the word is found i want the line it stands in and the previous line to be deleted.如果找到这个词,我希望它所在的行和前一行被删除。 I am able to get the line and the previos one and print them but i can not get my head around not to pass them to my outputfile.我能够获得该行和之前的行并打印它们,但我无法不将它们传递给我的输出文件。 Fe:铁:
in-put:输入:
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
out-put:输出:
This is not supposed to be deleted.
This is not supposed to be deleted.
This is not supposed to be deleted
I tried it with this code, but i keep getting a TypeError: 'str' object does not support item assignment我用这段代码试过了,但我一直收到一个 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)
You don't have to read the file at once.您不必立即读取文件。 Read the lines after each other, and store the current line, but write it out only after the next read, or not.逐行读取,并存储当前行,但仅在下一次读取后才将其写出,或者不写。
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
First keep track of which lines you want to copy:首先跟踪要复制的行:
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)
The trick with the deleted_previous_line
is necessary to ensure it does not delete too many lines if consecutive lines start with 'Text' or 'Titel'.如果连续行以“Text”或“Titel”开头,则必须使用deleted_previous_line
的技巧来确保它不会删除太多行。
Then write it to your output file然后将其写入您的输出文件
with open(file2, 'w') as f_out:
f_out.writelines(lines_to_keep)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.