The Python Oracle

Reading lines from text file in python (windows)

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Quirky Dreamscape Looping

--

Chapters
00:00 Question
01:23 Accepted answer (Score 3)
01:55 Answer 2 (Score 1)
02:21 Answer 3 (Score 0)
03:15 Answer 4 (Score 0)
03:44 Thank you

--

Full question
https://stackoverflow.com/questions/6229...

Answer 1 links:
[this]: http://docs.python.org/library/functions...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #windows #json #io

#avk47



ACCEPTED ANSWER

Score 3


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

foo
bar

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.




ANSWER 2

Score 1


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'




ANSWER 3

Score 0


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.




ANSWER 4

Score 0


Try the following in a Python interpreter to see what the language does:

open('test1.txt', 'wb').write(b'Hello\nWorld!')
open('test2.txt', 'wb').write(b'Hello\r\nWorld!')
print(list(open('test1.txt'))) # Shows ['Hello\n', 'World!']
print(list(open('test2.txt'))) # Shows ['Hello\n', 'World!']

Python does recognize the correct newlines. Instead of using strip on your strings, you might want to write myString.replace('\n', '') instead. Check the documentation:

>>> help(str.strip)
Help on method_descriptor:

strip(...)
    S.strip([chars]) -> str

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.

>>> help(str.replace)
Help on method_descriptor:

replace(...)
    S.replace(old, new[, count]) -> str

    Return a copy of S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.