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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,917评论 0 38
  • .bat脚本基本命令语法 目录 批处理的常见命令(未列举的命令还比较多,请查阅帮助信息) 1、REM 和 :: 2...
    庆庆庆庆庆阅读 8,224评论 1 19
  • 打开
    天之大任阅读 156评论 0 0
  • 生活,因为每天在发生着不同的事情而显得新鲜和有意义。 今天去童星看期末汇演,看到孩子们的成绩和笑脸,觉的从小培养的...
    爱吃糖糖的小魔女阅读 207评论 0 0
  • 做了互联网安利,邀请你合作的时候,你说等我赚两千块钱你来跟我做。等赚到两千块钱以后你说赚五千,你就来跟我做。那等我...
    Amway博爱阅读 175评论 0 0