[Tutor] (no subject)

Alan Gauld alan.gauld at btinternet.com
Thu May 15 08:05:37 CEST 2014


On 15/05/14 05:57, JEAN MICHEL wrote:

> with open ("period1.txt", 'r') as infile:
>      for line in infile:
>          values = line.split()
>          name.append(values[0] + ','+ values[1])
>          for line in infile:
>              values = line.split()
>              score1=float(values[2])
>              test1.append(score1)

I've just realised (I think) why you insist on nesting loops.
You are trying to get the lines in groups?

There are various ways to do this but the easiest here is
to use next():

with open(period.txt') as infile:
     for line in infile:
        process first line
        line = next(infile)  # get second line
        process second line
        line = next(infile)  # get third line
        etc...

That way you don't read the whole file at one go which your
nested loop "solution" does. The for loop will effectively
read every 5th line (if you have 4 next() calls inside it)

But you may have to use a try/except clause to catch
a StopIteration(?) exception if the file does not have
a multiple of 5 lines in it.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list