[Tutor] EOF function

Silviu Cojocaru silviucc@home.ro
Sat Jul 5 07:34:01 2003


On Sat, 5 Jul 2003, Magnus Lyck=E5 wrote:

> 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.
>=20
> f =3D file(filename)
> for line in f:
>      print line,
> f.close()
>=20
> If you are lazy, you can simply do
>=20
> for line in file(filename):
>      print line,
>=20
> 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.
>=20
> 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.
>=20
> 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.
>=20
> 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.

Yeah I never looked at the builtin objects . I imported "os" and used=20
readlines(). It was kinda intuitive like: "Hey where should the stuff=20
for manipulating files be? well there's no file module so lemme have a=20
look in the os module. Hey, here they are!" :)

Thanks for the pointers !

--=20
Registered Linux user #298569
This fortune is false.