Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line endings in python [duplicate]

Tags:

python

Possible Duplicate:
Handling \r\n vs \n newlines in python on Mac vs Windows

I'm a little bit confused by something, and I'm wondering if this is a python thing. I have a text file that uses Windows line endings ("\r\n"), but if I iterate through some of the lines in the file, store them in a list, and print out the string representation of the list to the console, it shows "\n" line endings. Am I missing something?

like image 952
Jon Martin Avatar asked May 28 '12 13:05

Jon Martin


People also ask

What is line endings in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text.

How do you copy a line in Python?

To copy text, just select it and hit Ctrl-C (Command-C on a Mac). If the highlight marking the selection disappears, that's normal and it means it's worked. To paste, use Ctrl-V (Command-V on a Mac).

How do you write multiple lines in Python?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line.


1 Answers

Yes, it's a python thing; by default open() opens files in text mode, where line endings are translated depending on what platform your code is running on. You'll have set newline='' in the open() call to ask for line endings to be passed through unaltered.

Python 2's standard open() function doesn't support this option, and only opening in binary mode would prevent the translation, but you can use the Python 3 behaviour by using io.open() instead.

From the documentation on open:

newline controls how universal newlines mode works (it only applies to text mode).

[...]

  • When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated.
like image 107
Martijn Pieters Avatar answered Oct 25 '22 00:10

Martijn Pieters