我有一个text file
,我正在尝试将所有文字添加到b
,直到单词Finish
出现。然而,这只是给了我一个infinte loop
我该如何解决这个问题
def extract(filename):
b = ''
line = f.readline()
while line:
line = f.readline().strip()
while line != 'Finish':
b = b + line
line = f.readline()
print(b)
感谢任何帮助
答案 0 :(得分:0)
如果第一个line
不是'Finish'
,则代码会卡在while
循环中。将while
更改为if
以检查line
是否为'Finish'
,然后转到下一行。当您从for循环或'Finish'
中点击break
,return b
时。
(感谢PM 2Ring)
答案 1 :(得分:0)
没有任何导入的简单代码:
文字文件:
something 1
something 2
something 3
Finish
something 4
something 5
something 6
<强>代码强>
file = open('try_text.txt', "r")
b = ''
for line in file:
if "Finish" in line:
to_append = line.strip().split("Finish")
b += to_append[0]
break
else:
b += line
print b
<强>输出:强>
something 1
something 2
something 3
答案 2 :(得分:-1)
您可以使用itertools.takewhile
,它将一直持续到结束或文件或符合其条件,例如:
from itertools import takewhile
with open(filename) as fin:
lines = (line.strip() for line in fin)
b = ''.join(takewhile(lambda L: L != 'Finish', lines))
对于以下文件:
something 1
something 2
something 3
Finish
something 4
something 5
something 6
将b
视为:
something 1something 2something 3