Reading lines from text file in python (windows) Reading lines from text file in python (windows) json json

Reading lines from text file in python (windows)


Python keeps the new line characters while enumerating lines. For example, when enumerating a text file such as

foobar

you get two strings: "foo\n" and "bar\n". If you don't want the terminal new line characters, you call strip().

I am not a fan of this behavior by the way.


See this.

Python is usually built with universal newline support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'


You need the strip() because "for line in file:" keeps the line terminators on the lines. It's not explicitly stated in the docs (at least in the 2.71 doc I'm looking at). But it functions in a fashion similar to file.readline(), which does explicitly state that it retains the newline.