我有文件類似下面(temp1目錄文件):搜索字符串,並打印從一個線以上在Python另一個搜索字符串
Basket1
10 Pens I have in Packet1
20 Books I have in Packet1
30 Red pens I have in Packet1
End here
Basket1
10 apples I have in Packet2
20 Mangos I have in Packet2
30 oranges I have in Packet2.
End here
我已經寫了下面的代碼,它將搜索之間的起始行和終止行並打印包括開始和結束行。
start_line = "Pens I have"
end_line = "End here"
print_lines = False
with open('temp1' , 'r') as f:
for line in f:
line = line.strip()
if (re.search(start_line, line)):
print_lines = True
if print_lines:
temp = open("temp2", 'a')
sys.stdout = temp
print line
if (re.search(end_line, line)):
print_lines = False
temp.close()
sys.stdout = sys.__stdout__
輸出我得到:
10 Pens I have in Packet1
20 Books I have in Packet1
30 Red pens I have in Packet1
End here
我需要幫助印刷線條從上面的文件從開始逐行TEMP2到行尾。以下是文件temp2的預期輸出。
Basket1
10 Pens I have in Packet1
20 Books I have in Packet1
30 Red pens I have in Packet1
End here
請註明你所面對 – JkShaw
喜JkShaw問題/問題,我需要打印到文件,從上面開始行到結束行之一。現在我只能打印從開始行到結束行 – kitty
你已經打印行到'temp2' –