假设我有一个包含以下内容的文本文件
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)
我在输出文件中有这个结果:
Good Morning
Hello World
hgjkkl
dfghjjk
fghjjj
Good Evening
Good
我的问题是我只想获取开始和结束之间的数据,而不是开始和开始或结束和结束之间的数据
请您参考如下方法:
大问题!这是一个桶问题,每个开始都需要结束。
之所以得到这个结果是因为有两个连续的'Start'。
最好将信息存储到某处,直到触发“结束”。
infile = open('scores.txt','r')
outfile= open('testt.txt','w')
copy = False
for line in infile:
if line.strip() == "Start":
bucket = []
copy = True
elif line.strip() == "End":
for strings in bucket:
outfile.write( strings + '\n')
copy = False
elif copy:
bucket.append(line.strip())
