Populating a list

Jeremy Whetzel lists at toadmail.com
Sun Dec 9 17:24:58 EST 2001


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



More information about the Python-list mailing list