Populating a list

Tim Daneliuk tundra at tundraware.com
Tue Dec 11 00:10:08 CET 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.
> 
> 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

I think the following works portably so you do not have to fiddle w/ EOL
conventions:

f=open("xxx.txt")
x=f.read().splitlines()
f.close()

x is now populated with the content of the line regardless of how it ends
(or at least this works on a FreeBSD system using a WinDoze text file).

As someone else pointed out here, the [:-1] idiom has the problem that
it may truncate the last character of the file if the last line does not
end with the unwanted character.  Similarly, chopping trailing whitespace is
semantically very different than handling differing EOL conventions (though
it may work on text files, there may be applications where the embedded
trailing whitespace may be important, say if a pagefeed is embedded at the
end of a line...).

In general, this is system level stuff that ought to be handled by the system
and/or language whenever possible, not the program logic...
-- 
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com



More information about the Python-list mailing list