Line terminators in Python?

Chris Warrick kwpolska at gmail.com
Fri Sep 29 14:26:52 EDT 2017


On 29 September 2017 at 19:54, Stefan Ram <ram at zedat.fu-berlin.de> wrote:
>   In some languages, printing »'\n'«, the Unicode code point 10,
>   will have the effect of printing a line terminator, which might
>   mean that the output device actually receives »\r\n«.
>
>   The line terminator ostensibly depends on the operating
>   system, but actually it depends on the output system. E.g.,
>   under one operating system the console might accept another
>   set of line separators than an editor. (Under Windows,
>   »wordpad« accepts »\n«, while »notepad« requires »\r\n«.)
>
>   What is the recommended way to terminate a line written with
>   Python? Is it »\n« or something else? For example, in Java,
>   in some cases, one should terminate the line with the value
>   of »java.lang.System.lineSeparator()« which might or might
>   not be equal to the value of »"\n"«.
>
>   Does it possibly depend on the entity being written to, which
>   might be
>
>       - the Python console,
>       - the IDLE console,
>       - the operating system console or
>       - a text file?

It depends on the mode used to open the output file.
https://docs.python.org/3/library/functions.html#open

sys.stdout is opened in 'w' mode by default (writing, text mode). Text
mode means that non-Unix newlines (\r\n, \r) are translated to '\n'
when reading, and '\n' is translated to the system local newline when
writing. So, if you’re working in text mode (which also handles
encodings and returns Unicode strings on Python 3), you can just
assume '\n'.

If you’re curious what the local newline is, look at os.linesep:
https://docs.python.org/3/library/os.html#os.linesep

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16



More information about the Python-list mailing list