Idiomatic portable way to strip line endings?

Tim Hammerquist tim at vegeta.ath.cx
Sun Dec 16 09:21:34 EST 2001


I've been trying to figure out the canonical way to strip the line
endings from a text file.

In general, I can use:

    line = line[:-1]
or
    del line[-1:]

to strip the last character off the line, but this only works on
operating systems that have a one-byte line separator like Unix/Linux
('\n').  The Win32 line separator is 2-bytes ('\r\n'), so this
solution is not portable.

Perl (the dreaded word!) had a chomp() function that worked similar
to the following. (The original modified its argument and returned the
number of bytes chomped.)

    def chomp(line):
        if line.endswith(os.linesep):
            return line[:line.rindex(os.linesep)]
        return line

I've seen several other solutions, including:

    line.replace(os.linesep, '')

The above works when iterating over text files, but fails if only a
final linesep should be stripped. OTOH, I've seen the non-portable:

    line = line[:-1]

in production code.

Is there a common idiom for this procedure? What do you use with
portability in mind?

TIA,
Tim Hammerquist
-- 
Did I listen to pop music because I was miserable...
Or was I miserable because I listened to pop music?
    -- John Cusack, "High Fidelity"



More information about the Python-list mailing list