Using the While Loop
Greg Jorgensen
gregj at pobox.com
Sat Jun 16 13:38:53 EDT 2001
Python assignments are statements, not expressions. You are probably used to
C, C++, or Java. In Python the statement "line = myfile.readline()" is not
an expression and doesn't have a value, so it's not syntactically valid
following if or while. Your second example is the canonical Python form for
reading lines sequentially from a file.
Of course there are alternatives. The file method readlines() reads the
entire file into a list of lines, so you can iterate over the file like
this:
for line in f.readlines():
print line
That's not efficient for large files, though, because the entire file is
read into memory by readlines(). Python 2.1 introduced the more efficient
xreadlines module, which lets you efficiently iterate over lines in a file
without reading it all into memory first:
import xreadlines
for line in xreadlines.xreadlines(f):
print line
Greg Jorgensen
PDXperts LLC
Portland, Oregon, USA
gregj at pdxperts.com
"Mike Johnson" <ffp_randjohnson at yahoo.com> wrote in message
news:20010616.101117.1469262009.1725 at behemoth.miketec.com...
> Hello all,
>
> I don't see why this first code snippet won't work, but I can't find any
> pointers in the documentation.
>
> --------------------------------------
> #!/usr/bin/python2.1
>
> myfile = open ("/tmp/messages")
>
> while line = myfile.readline():
> print line
> --------------------------------------
>
> But this works fine:
> --------------------------------------
> #!/usr/bin/python2.1
>
> myfile = open ("/tmp/messages")
>
> line = myfile.readline()
> while line:
> print line
> line = myfile.readline()
> --------------------------------------
>
> Thanks for any help!
>
> - Mike Johnson
>
>
> -----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
> http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
> -----== Over 80,000 Newsgroups - 16 Different Servers! =-----
More information about the Python-list
mailing list