Strange behaviour with os.linesep

Vincent Vande Vyvre vincent.vandevyvre at swing.be
Wed Jul 24 03:02:37 EDT 2013


Le 23/07/2013 17:25, Steven D'Aprano a écrit :
> 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
>
>
>
In fact, in my code, the original file is open in binary mode, the line 
separator is translate to \n and it is parsed by the module tokenise.

I'm not a Windows user but my code must be run also on Win, this is the 
reason of the usage of os.linesep in writting.

So, now I found the solution, just write the file in binary mode and now 
it is correctly open with all the editors.

Thanks all

-- 
Vincent V.V.
Oqapy <https://launchpad.net/oqapy> . Qarte 
<https://launchpad.net/qarte> . PaQager <https://launchpad.net/paqager>



More information about the Python-list mailing list