【发布时间】:2025-12-06 07:35:01
【问题描述】:
假设我有一个包含以下内容的文本文件
fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk
Start
hgjkkl
dfghjjk
fghjjj
Start
Good Evening
Good
End
我写了以下代码:
infile = open('test.txt','r')
outfile= open('testt.txt','w')
copy = False
for line in infile:
if line.strip() == "Start":
copy = True
elif line.strip() == "End":
copy = False
elif copy:
outfile.write(line)
我在 outfile 中有这个结果:
Good Morning
Hello World
hgjkkl
dfghjjk
fghjjj
Good Evening
Good
我的问题是我只想获取 start 和 end 之间的数据,而不是 start 和 start 或 End 和 End 之间的数据
【问题讨论】:
-
您应该尝试使用缓冲区变量来存储“开始”之后遇到的内容,直到遇到“结束”然后将其写入文件。