2015-09-09 29 views
1

示例文件保持Linies從一個文件中的兩個表達式(獨家)之間:使用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) 
+0

你有一個'tag_found'變量。你需要同時具有'tag1_found'和'tag2_found',並且只有當一個爲真而不是另一個時纔打印。 –

回答

2

你只需要在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)