Correct way to write line to file?

后端 未结 14 2219
日久生厌
日久生厌 2020-11-21 06:27

I\'m used to doing print >>f, \"hi there\"

However, it seems that print >> is getting deprecated. What is the recommended way t

14条回答
  •  耶瑟儿~
    2020-11-21 06:38

    Regarding os.linesep:

    Here is an exact unedited Python 2.7.1 interpreter session on Windows:

    Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
    win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> os.linesep
    '\r\n'
    >>> f = open('myfile','w')
    >>> f.write('hi there\n')
    >>> f.write('hi there' + os.linesep) # same result as previous line ?????????
    >>> f.close()
    >>> open('myfile', 'rb').read()
    'hi there\r\nhi there\r\r\n'
    >>>
    

    On Windows:

    As expected, os.linesep does NOT produce the same outcome as '\n'. There is no way that it could produce the same outcome. 'hi there' + os.linesep is equivalent to 'hi there\r\n', which is NOT equivalent to 'hi there\n'.

    It's this simple: use \n which will be translated automatically to os.linesep. And it's been that simple ever since the first port of Python to Windows.

    There is no point in using os.linesep on non-Windows systems, and it produces wrong results on Windows.

    DO NOT USE os.linesep!

提交回复
热议问题