我有如下文件(temp1文件):
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
因为你需要
Basket1
来打印,所以你的start_line
必须是Basket1
,而在第一行之后,你需要Pens I have
我把它用作“中间行”您可以使用正则表达式搜索字符串,使用它读取和写入文件,您可以执行以下操作:
示例:
相关问题 更多 >
编程相关推荐