Populating a list

Kevin Cazabon kevin at cazabon.com
Mon Dec 10 01:38:54 EST 2001


The reason you'd get an error is that you have no handle on the open
file.  (f is a list, not a file pointer).  The file is still open
however, you just have no way to close it.  I'd hope that Python would
close the file once it goes out of scope, but I couldn't guarantee it.

To be safe, I'd suggest doing the open and readlines separately, so
you can keep a reference to the file, then use it to close the file.

f = open(filename, "r")
crap = [item.rstrip() for item in f.readlines()]
f.close()


Just MHO
Kevin.

> Main reason why I mentioned the thing of leaving out the f.close() at
> the end is because, for me at least, it generates an error if I try to
> close it since it's not really the open file, but a list of all the
> lines read from the file.  Otherwise I definitely would close it, too.
> 
> *scratches head*  Unless I'm doing something wrong...
> 
> Jeremy



More information about the Python-list mailing list