Populating a list

Chris Barker chrishbarker at attbi.com
Tue Dec 11 13:00:35 EST 2001


Tim Daneliuk wrote:

> Oh, never mind, the original version does work - I fatfingered the test
> code... Sigh.  The modified version does work, but is limited to DOS type
> text files, whereas the original version does appear to be platform neutral.

Actually, this is not quite right. DOS text files are delineated with a
"\r\n", and Unix text files with "\n". Python internally expects "\n".
If you read a DOS file on a DOS compatable system (windows*, OS/2,
whatever) that was opened as a text file, the translation will be done
for you, and you will have "\n" intenally, so either splitlines() or
split("\n") will work.

If, on the other hand, you read a DOS style text file on a *nix sytem,
no tranlatin will be done and you will have "\r\n", and splitlines()
will work, but split("\n") will leave a "\r" on the line. An example:

>>> unixtext = "this is a line\nthis is another"
>>> dostext = "this is a line\r\nthis is another"
>>> unixtext.split("\n")
['this is a line', 'this is another']
>>> dostext.split("\n")
['this is a line\r', 'this is another']
 # see the extra "\r" ?

>>> unixtext.splitlines()
['this is a line', 'this is another']
>>> dostext.splitlines()
['this is a line', 'this is another']

splitlines takes care of it.

By the way, I had never notices splitlines() before, thanks for pointing
it out.

On another note: There has been talk on Python-dev about having a
"universal" text file type that would translate non-native text files
automagiacally. I'm not sure if any real code has been written yet to
support it, however.

-Chris

-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at attbi.net                ---           ---           ---
                                     ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list