Populating a list
Alex Martelli
aleaxit at yahoo.com
Sun Dec 9 17:44:55 EST 2001
mlorfeld wrote:
> 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.
Yes, the \n character, also known as \012, is indeed part of each line.
> 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
Perfectly correct code. If you prefer to remove the last character of each
line, or perform other alterations, try:
states = [ line[:-1] for line in f.readlines() ]
instead of just using "states = f.readlines()", which does no alterations.
Akex
More information about the Python-list
mailing list