Beginner question : skips every second line in file when using readline()

Alex Martelli aleax at aleax.it
Mon Oct 20 10:18:01 EDT 2003


peter leonard wrote:

> 
> Thanks for point out my error. This works fine now :
> 
> datafile ="C:\\Classifier\Data\\test.txt"
> dataobject = open(datafile,"r")
> 
> 
> line = dataobject.readline()
> while line.strip():
>     print line
>     line = dataobject.readline()

So would the simpler:

  for line in dataobject:
      if not line.strip(): break
      print line

Applicable principle: "Once, and only once".  Don't
have two calls to dataobject.readline if you can
avoid it.  If files weren't directly iterable, still:

  for line in iter(dataobject.readline, ''):
      if not line.strip(): break
      print line

would be preferable (avoids duplicating the call).
Since files ARE directly iterable, of course, it's
better to use that capability directly.


Alex





More information about the Python-list mailing list