Strange behaviour with os.linesep

Steven D'Aprano steve+comp.lang.python at
Tue Jul 23 17:25:12 CEST 2013

On Tue, 23 Jul 2013 13:42:13 +0200, Vincent Vande Vyvre wrote:

> On Windows a script where de endline are the system line sep, the files
> are open with a double line in Eric4, Notepad++ or Gedit but they are
> correctly displayed in the MS Bloc-Notes.

I suspect the problem lies with Eric4, Notepad++ and Gedit. Do you 
perhaps have to manually tell them that the file uses Windows line 

I recommend opening the file in a hex editor and seeing for yourself what 
line separators are used.

> Example with this code:
> ----------------------------------------------
> # -*- coding: utf-8 -*-
> import os
> L_SEP = os.linesep
> def write():
>      strings = ['# -*- coding: utf-8 -*-\n',
>                  'import os\n',
>                  'import sys\n']
>      with open('', 'w') as outf:
>          for s in strings:
>              outf.write(s.replace('\n', L_SEP))
> write()
> ----------------------------------------------
> The syntax `s.replace('\n', L_SEP)`is required for portability.

I don't think it is. Behaviour is a little different between Python 2 and 
3, but by default, Python uses "Universal Newlines". When you open a file 
in text mode, arbitrary line separators should be automatically 
translated to \n when reading, and \n will be automatically translated to 
os.line_sep when writing.

Some further discussion here:


More information about the Python-list mailing list