Idiomatic portable way to strip line endings? (fwd)

Martin Bless m.bless at gmx.de
Mon Dec 17 05:25:51 EST 2001


[Tomasz Lisowski]:
>Why not use the string.rstrip() function?

Because (1) rstrip() removes ALL whitespace chars ('\t\x20\r\n...')
and because (2) rstrip() is greedy. Removes all and not just one. It's
simply something different.

I like the elsewhere here presented "chomp()" version.

And to clarify:

  for line in open(fname,'rb').readlines():
    print `line`

on a windows system will yield very well lines ending with '\n' except
maybe - as documented and in general - the last one. Only difference
to open(fname,'r'): all \r are left untouched.

So contrary to what someone suspected you are not in "great
difficulties" if you open files binary (at least on a windows
systems). You just get get each and every byte from the infile, which
is sometimes what you need. readlines() still works fine.

You just have the *opportunity* to distinguish between carriage
return, line feed or both. How could you control your good old
electric typewriter better? ;-) Let it dance!

Martin



More information about the Python-list mailing list