Strange behaviour with os.linesep
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Tue Jul 23 11:25:12 EDT 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
separators?
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('writetest.py', '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.
http://docs.python.org/3/library/functions.html#open
http://docs.python.org/2/library/functions.html#open
Some further discussion here:
http://stackoverflow.com/questions/12193047/is-universal-newlines-mode-
supposed-to-be-default-behaviour-for-open-in-python
--
Steven
More information about the Python-list
mailing list