Domanda

I've got multiple file where I want to parse variable numbers of lines. Basically down to a line containing the string Date:.

The code I'm using is:

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)]

I keep getting a StopIteration error and I can't figure out why. The type for i is an int, so I assumed that it would work.

Any suggestions?

È stato utile?

Soluzione

next() gives you a StopIteration because you've already consumed it in your loop (you aren't starting at the beginning again). Try adding to the list as you go, instead of in another loop at the end:

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

Altri suggerimenti

You can also use itertools.takewhile() to get all the lines until there is a Date: inside:

from itertools import takewhile

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

print data

It depends what version of python you have on python 3 the following code work\

   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)]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top