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

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值