Populating a list

Jeremy Whetzel lists at toadmail.com
Sun Dec 9 18:00:42 EST 2001


"A. Keyton Weissinger" <keyton at weissinger.org> writes:

> You can also do this:
> 
> states = []
> f=open('/home/mlorfeld/states.txt', 'r+').readlines()
> for i in f:
>   states.append(i.rstrip())
> print states
> 
> The rstrip() method, as you can probably guess, strips white spaces from the
> RIGHT end of the string.


Nifty tip... thanks.  =0)


> Not sure on the file closing that Jeremy mentioned (I'm also not that
> adept). But I thought it was probably good to do so -- just in case:
> 
> states = []
> f=open('/home/mlorfeld/states.txt', 'r+').readlines()
> for i in f:
>   states.append(i.rstrip())
> f.close()
> print states


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