Python file.write creating extra carriage return Python file.write creating extra carriage return windows windows

Python file.write creating extra carriage return


\n is converted to os.linesep for files opened in text-mode. So when you write os.linesep to a text-mode file on Windows, you write \r\n, and the \n gets converted resulting in \r\r\n.

See also the docs:

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.


With Python 3

open() introduces the new parameter newline that allows to specify a string which any occurrence of \n will be translated to.

Passing an empty string argument newline='' disables the translation, leaving the new line char as it is. Valid for text mode only.

From the documentation

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.


Text files have different line endings on different operating systems, but it's convenient to work with strings that have a consistent line ending character. Python inherits the convention from C of using '\n' as the universal line ending character and relying on the file read and write functions to do a conversion, if necessary. The read and write functions know to do this if the file was opened in the default text mode. If you add the b character to the mode string when opening the file, this translation is skipped.