Populating a list

A. Keyton Weissinger keyton at weissinger.org
Sun Dec 9 17:58:56 EST 2001


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.

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

Keyton

-----Original Message-----
From: python-list-admin at python.org
[mailto:python-list-admin at python.org]On Behalf Of Jeremy Whetzel
Sent: Sunday, December 09, 2001 5:25 PM
To: python-list at python.org
Subject: Re: Populating a list


matt at lorfeld.com (mlorfeld) writes:

> I am new to python (about 72 hours into learning), and am having
> problems with reading a file (sate abbreviations) with one item per
> line and populating each line into a list.  The problem is that each
> item ends with \012 after each state ie WI\012.
>
> Here is the code that I am using:
>
> f=open('/home/mlorfeld/states.txt', 'r+')
> states=f.readlines()#populates a list from file
> f.close
> print states

The \012 is a newline character, from what I understand.  There's a
couple of ways you could do this, but I personally (and there may be
disagreement on this) would do it this way:

states = []
f=open('/home/mlorfeld/states.txt', 'r+').readlines()
for i in f:
  states.append(i[:-1])
print states

The biggest reason why I'd do it this way is because then you don't have
to worry about closing the file at the end.  I'm probably showing my
green behind the ears doing it this way, but hey, it's a learning
experience.  =0)

Jeremy
--
http://mail.python.org/mailman/listinfo/python-list






More information about the Python-list mailing list