Python w / o \ n read lines

Will this work on all platforms? I know that Windows does \ r \ n, and remember that the rumor mac works \ r, and linux - \ n. I ran this code in windows to make it look great, but did you know its cross platform?

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

First of all, there is universal newline support

Secondly: use line.strip(). Use line.rstrip('\r\n')if you want to keep spaces at the beginning or end of a line.

Oh and

print '"%s"' % line

or at least

print '"' + line + '"'

may seem a little nicer.

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

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

, , str.splitlines :

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

:

line = line.rstrip('\r\n')
+4

line = line [: - 1]

A line cannot have a trailing new line if it is the last line of the file.

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

0
source

Source: https://habr.com/ru/post/1702665/


All Articles