Eleganz way to get rid of \n

Fredrik Lundh fredrik at pythonware.com
Mon Sep 1 16:45:24 CEST 2008


Hans Müller wrote:

> I'm quite often using this construct:
> 
> for l in open("file", "r"):
>     do something
> 
> here, l contains the \n or \r\n on windows at the end.

nope -- if you open a file in text mode (without the "b"), the I/O layer 
will translate "\r\n" to "\n" on Windows.

if you want even more robust behaviour, use the "U" flag (for universal 
newlines); that'll handle old-style Mac files too.

(as others have pointed out, a plain rstrip() is usually the best choice 
anyway.  giving meaning to trailing whitespace in text files is usually 
a really lousy idea).

</F>




More information about the Python-list mailing list