The Python Oracle

Reading lines from text file in python (windows)

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Cosmic Puzzle

--

Chapters
00:00 Reading Lines From Text File In Python (Windows)
00:58 Answer 1 Score 0
01:21 Answer 2 Score 1
01:42 Accepted Answer Score 3
02:07 Answer 4 Score 0
02:44 Thank you

--

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

--

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.