reading line by line

Greg Jorgensen gregj at pobox.com
Sun Jan 14 16:28:05 EST 2001


In article <I4i86.290010$_5.65173315 at news4.rdc1.on.home.com>,
  msoulier at storm.ca wrote:
>
>     Hey people. I know that the readlines() method in file objects
allows line
> by line reading, but it seems to read the entire file first, which is
far too
> memory intensive if you're reading a massive file. Now, I know that
you can do
> this:
>
> file = open(filename, "r")
> line = file.readline()
> while line:
>     # work on file
>     line = file.readline()
>
>     But I don't like the initial readline() call to initialize line.

The standard Python idiom described by Frederik Lundh is the way to
read a single file line by line. You should also see the fileinput
module. That module can read multiple files, and gives you an iterator
for the file(s):

import fileinput

for line in fileinput.input(filename):
    print line


--
Greg Jorgensen
Portland, Oregon, USA
gregj at pobox.com


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list