[Tutor] EOF function

Magnus Lyckå magnus@thinkware.se
Sat Jul 5 07:06:15 2003


At 13:15 2003-07-05 +0300, Silviu Cojocaru wrote:
>On Sat, 5 Jul 2003, Magnus Lyckå wrote:
>
> > At 17:16 2003-07-04 +0300, Silviu Cojocaru wrote:
> > >I want to write a function that will return 1 if EndOfFile is reached
> > >and 0 if not.
> >
> > Why? What are you *really* trying to achieve.
> > This is nothing you normally need in Python.
>
>I was trying to read a file line by line. Being used to Pascal I tried
>the Pascal way :) Then a post to the tutor list enlightened me. There
>was something about using readlines(). So I did :) It shrank the code I
>have already written and working to half its size, and it even worked
>better :)

But .readlines() reads the whole file at once, and puts it in a list.
That might be a problem with a big file. With modern python versions,
you can simply iterate over the file object.

f = file(filename)
for line in f:
     print line,
f.close()

If you are lazy, you can simply do

for line in file(filename):
     print line,

Note that each line will end with a line-feed (or whatever you
have on your platform). That's why I end the print statement
with a comma--do avoid double line feeds.

Note that you don't explicitly close the file in the shorter version.
I the current C based version of Python, I think it will be closed as
soon as the loop ends, but the language doesn't guarantee that, and in
the Java implementation of Python--Jython, the file might not be closed
just yet. Java's garbage collection handles that.

This means that there might be problems with a long-running program,
or if you want to open the same file for writing further ahead.

In other words, you might want to get a reference to the file object
and close it explicitly as soon as you can unless you know that it's
ok to leave it open until the program terminates--at least if you want
to be sure that your program works as well in five years as it does now.


--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language