Populating a list

Chris Barker chrishbarker at attbi.com
Mon Dec 10 19:57:29 CET 2001


Bruce Eckel wrote:
> I would probably do it like this:
> lines = [l.rstrip() for l in open('filename')]

hey, I was about to post that!

I've also used map() a lot:

lines = map(string.strip, open('filename').readlines())

> Using rstrip(), I believe, handles more general cases (some oses
> have two characters to end a line, rather than just one).

I use strip() because whitespace athe beginning or end of line is
usually garbage in my applications.

It does handle more general cases, but if the file is opened as a text
file (the default), Python will always translate the line endings into
its native form (one \n). If the file is not native to the system you
are running on, you are SOL.

Kevin Cazabon wrote:
> > f=open('/home/mlorfeld/states.txt', 'r+').readlines()

> 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.

Python does close the file when it's reference count goes to zero, which
will happen as soon as that line is done processing. I'm pretty sure it
is guaranteed, I certainly have never had a problem with it. That's
what's nice about Python's reference counting scheme.

-Chris


-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at attbi.net                ---           ---           ---
                                     ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list