views:

345

answers:

3

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 + "\""
+13  A: 

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.

Finally, you can iterate over the lines in a file like this:

for line in f:
    print '"' + line.strip('\r\n') + '"'
hop
This will strip off all leading and trailing whitespace, not just the line ending.
Dave Ray
+1: open( file, "rU" ) for universal newline.
S.Lott
concise, complete, to the point.
chryss
+4  A: 

Try this instead:

line = line.rstrip('\r\n')
Dave Ray
A: 

line = line[:-1]

A line can have no trailing newline, if it's the last line of a file.

As suggested above, try universal newlines with rstrip().

bobince