acidzombie24 acidzombie24 - 2 months ago 7
Python Question

python reading lines w/o \n?

Would this work on all platforms? i know windows does \r\n, and remember hearing mac does \r while linux did \n. I ran this code on windows so it seems fine, but do any of you know if its cross platform?

while 1:
line = f.readline()
if line == "":
break
line = line[:-1]
print "\"" + line + "\""

hop hop
Answer

First of all, there is universal newline support

Second: just use line.strip(). Use line.rstrip('\r\n'), if you want to preserve any whitespace at the beginning or end of the line.

Oh, and

print '"%s"' % line

or at least

print '"' + line + '"'

might look a bit nicer.

You can iterate over the lines in a file like this (this will not break on empty lines in the middle of the file like your code):

for line in f:
    print '"' + line.strip('\r\n') + '"'

If your input file is short enough, you can use the fact that str.splitlines throws away the line endings by default:

with open('input.txt', 'rU') as f:
    for line in f.read().splitlines():
        print '"%s"' % line

The readline() and readlines() methods of codecs.StreamReader offer a similar argument that you can use for iterating over longer files.

Comments