Populating a list

Bruce Eckel Bruce at EckelObjects.com
Sun Dec 9 23:02:09 EST 2001


I would probably do it like this:
lines = [l.rstrip() for l in open('filename')]
In Python 2.2 you don't have to say "readlines", as open() produces
an iterator.
Using rstrip(), I believe, handles more general cases (some oses
have two characters to end a line, rather than just one).

*********** REPLY SEPARATOR  ***********

On 12/9/01 at 8:01 PM A. Keyton Weissinger wrote:

>So we're clear. You can either do it this way:
>
>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.
>
>or (from Mr. Martelli -- I like this one better):
>
>f = open('/home/mlorfeld/states.txt', 'r+')
>states = [ line[:-1] for line in f.readlines() ]
>f.close()
>
>Sorry for the misinformation, folks.
>
>Keyton
>
>
>-- 
>http://mail.python.org/mailman/listinfo/python-list



Most current information can be found at:
http://www.mindview.net/Etc/notes.html
===================
Bruce Eckel    http://www.BruceEckel.com
Contains free electronic books: "Thinking in Java 2e" & "Thinking
in C++ 2e"
Please subscribe to my free newsletter -- just send any email to:
join-eckel-oo-programming at earth.lyris.net
My schedule can be found at:
http://www.mindview.net/Calendar
===================






More information about the Python-list mailing list