微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python 文本模式读写文件时 不应使用 os.linesep 简介

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

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐