美文网首页
python笔记:文本模式读写文件时不应使用os.linesep

python笔记:文本模式读写文件时不应使用os.linesep

作者: 哈莉_奎茵 | 来源:发表于2018-02-17 19:28 被阅读0次

    os.linesep官方文档

    The string used to separate (or, rather, terminate) lines on the current platform. This may be a single character, such as '\n' for POSIX, or multiple characters, for example, '\r\n' for Windows. 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.

    如上,os.linesep是用来分割文件的每一行(即文件结束符),由于在不同操作系统下文件结束符不一定相同,所以os.linesep是跨平台的文件描述符,比如在Windows平台上是'\r\n',在Linux平台上则是'\n'

    Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
    Type "copyright", "credits" or "license()" for more information.
    >>> import os
    >>> os.linesep
    '\r\n'
    
    Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
    [GCC 5.4.0 20160609] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> os.linesep
    '\n'
    

    但是以open默认的文本模式读写时,'\n'会被自动转换成'\r\n'。在Windows平台实验如下

    >>> with open(r'D:\test.txt', 'w') as f:
              f.write(os.linesep)
    
              
    2
    >>> with open(r'D:\test.txt', 'rb') as f:
              f.read()
    
              
    b'\r\r\n'
    

    本来是要写入结束符'\r\n',结果由于python自动把'\n'替换成'\r\n'导致写入的是'\r\n\n'。因此按照官方的建议,此时使用'\n'代替os.linesep即可。
    不过在二进制模式下,为文本文件添加换行符的操作用os.linesep来实现跨平台更好。

    >>> with open(r'D:\test.txt', 'wb') as f:
              f.write(os.linesep.encode())
    
              
    2
    >>> with open(r'D:\test.txt', 'rb') as f:
              f.read()
    
              
    b'\r\n'
    

    参考资料
    https://stackoverflow.com/questions/21636213/why-you-shouldnt-use-os-linesep-when-editing-on-text-mode

    相关文章

      网友评论

          本文标题:python笔记:文本模式读写文件时不应使用os.linesep

          本文链接:https://www.haomeiwen.com/subject/xnxvtftx.html