使用 python 将 Linies 保留在文件中的两个表达式(不包括)之间
Keep Linies between two expressions (exclusive) from a file using python
示例文件:
aaa
bbb
ccc
ddd
start of a pattern
apple
orange
red
green
blue
end of a pattern
eee
fff
www
我需要保留两个标签之间的线条:TAG1 and TAG2
我可以删除 TAG1
之前的行。坚持如何删除 TAG2
之后的行?
TAG1 = 'start of a pattern'
TAG2 = 'end of a pattern'
tag_found = False
with open('input.txt') as in_file:
with open('output.txt', 'w') as out_file:
for line in in_file:
if not tag_found:
if line.strip() == TAG1:
tag_found = True
else:
out_file.write(line)
你只需要在else块中添加一个条件:
else:
if line.strip() == TAG2:
break # Break out of the loop
out_file.write(line)
但是你可以在没有任何中间变量的情况下做到这一点:
while next(in_file).strip() != TAG1: # Consume all lines up to TAG1
pass
for line in in_file:
if line.strip() == TAG2: # Break at TAG2
break
out_file.write(line)
示例文件:
aaa
bbb
ccc
ddd
start of a pattern
apple
orange
red
green
blue
end of a pattern
eee
fff
www
我需要保留两个标签之间的线条:TAG1 and TAG2
我可以删除 TAG1
之前的行。坚持如何删除 TAG2
之后的行?
TAG1 = 'start of a pattern'
TAG2 = 'end of a pattern'
tag_found = False
with open('input.txt') as in_file:
with open('output.txt', 'w') as out_file:
for line in in_file:
if not tag_found:
if line.strip() == TAG1:
tag_found = True
else:
out_file.write(line)
你只需要在else块中添加一个条件:
else:
if line.strip() == TAG2:
break # Break out of the loop
out_file.write(line)
但是你可以在没有任何中间变量的情况下做到这一点:
while next(in_file).strip() != TAG1: # Consume all lines up to TAG1
pass
for line in in_file:
if line.strip() == TAG2: # Break at TAG2
break
out_file.write(line)