从Python中的文件中提取

时间:2017-03-25 07:45:19

标签: python

我有一个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)

感谢任何帮助

3 个答案:

答案 0 :(得分:0)

如果第一个line不是'Finish',则代码会卡在while循环中。将while更改为if以检查line是否为'Finish',然后转到下一行。当您从for循环或'Finish'中点击breakreturn 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