acidzombie24 acidzombie24 - 1 year ago 80
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 == "":
line = line[:-1]
print "\"" + line + "\""

hop hop
Answer Source

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
        print '"%s"' % line

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download