Is there an easy way to get the type of line ending that the current operating system uses?
4 Answers
If you are operating on a file that you opened in text mode, then you are correct that line breaks all show up as '\n
'. Otherwise, you are looking for os.linesep
.
From http://docs.python.org/library/os.html:
os.linesep
The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows. Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

- 74,139
- 30
- 130
- 136
-
When you mean by "text mode", do you mean by non-binary mode in general? – theX Oct 03 '20 at 18:47
-
And if you're wondering, per https://docs.python.org/3/library/functions.html#open-newline-parameter, this also works while writing files out. – APerson Oct 02 '21 at 08:00
Oh, I figured it out. Apparently, PEP-278 states the following:
Any line ending in the input file will be seen as a '\n' in Python, so little other code has to change to handle universal newlines.

- 98,895
- 36
- 105
- 117
If specify test resp. binary properly when opening files, and use universal newlines, you shouldn't have to worry about different newlines most of the time.
But if you have to, use os.linesep

- 19,298
- 7
- 47
- 66
os.linesep is important as it depends (as the name implied:)) on os.
E.g. on Windows, it is not "\n" but rather "\r\n".
But if you don't care about multi-platform stuff you can just use '\n'.

- 300
- 3
- 11
-
this directly contradicts the accepted answer which quotes the documentation, which recommends to simply use \n even on windows-textfiles (as they will be converted to \r\n when the file is opened in text-mode) – julaine Mar 25 '23 at 15:06