如何在range()函数中使用变量来选择动态范围?

时间:2014-04-07 18:45:57

标签: python range

我有多个文件,我想解析可变数量的行。基本上是一行包含字符串Date:

我正在使用的代码是:

with open('MyFile.txt') as text:
    count=0
    i=0
    while i == 0:
        for line in text:
            count+=1
            if 'Date:' in line:
                i = count
                break
    head = [text.next() for x in range(i)]

我一直收到StopIteration错误,我无法弄清楚原因。 i的类型是一个int,所以我认为它会起作用。

有什么建议吗?

3 个答案:

答案 0 :(得分:1)

next()为您提供StopIteration,因为您已经在循环中消耗了它(您不会再次从头开始)。尝试添加到列表中,而不是在最后的另一个循环中添加:

head = []
with open('MyFile.txt') as text:
    for line in text:
        if 'Date:' in line:
            break
        head.append(line)

答案 1 :(得分:1)

您还可以使用itertools.takewhile()获取所有内容,直到内部有Date:

from itertools import takewhile

with open('MyFile.txt') as text:
    data = list(takewhile(lambda line: 'Date:' not in line, text))

print data

答案 2 :(得分:0)

这取决于你在python 3上有什么版本的python以下代码工作\

   text = open('text.txt', 'r')
    count=0
    i=0
    while i == 0:
        for line in text:
            count+=1
            if 'Date:' in line:
                i = count
                break
    head = [text.next() for x in range(i)]