栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

[Python]

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[Python]

场景
  1. 在linux上执行shell脚本时出现$’r’:command not found错误. 在Windows上打开.sh文件是能正常显示的,怎么回事?

  2. 使用Python生成的utf-8格式的文件为什么print函数设置了end="n"还是输出十六进制的0D0A, 不应该只输出0A吗?

说明
  1. 在Linux上的Bash shell脚本文件是严格规定了必须n(0A)作为换行符, 因此如果在Windows上生成的文件以rn作为换行符的话, 执行这个shell文件时会报错的。

  2. 在Python上使用内置open()函数来创建一个文本文件对象TextIObase超类,而具体的实现子类是,可以通过print(type(f))获得.

  3. 这个open()函数[3]是有坑的,在输出流的描述里,如果newline不指定,那么任何的n会自动转义为系统的默认换行符,也就是在Windows下生成的文件,遇到n写入自动会转换为rn, 也就是十六进制0D0A, 所以生成的文件放到Linux上执行就会报上边的错误。解决办法就是在使用open()时指定newline参数。

newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', 'n', 'r', and 'rn'. It works as follows:
    
    - When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in 'n', 'r', or 'rn', and these are translated into 'n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
    
    - When writing output to the stream, if newline is None, any 'n' characters written are translated to the system default line separator, os.linesep. If newline is '' or 'n', no translation takes place. If newline is any of the other legal values, any 'n' characters written are translated to the given string.
  1. 在各系统里的换行符要求:
Windows: rn:
Linux: n
macOS: 可以是r或者rn
例子
  1. 这里在Windows系统下输出文件,并使用winhex查看文件的十六进制。

if __name__ == '__main__':
    print("hello world")
    f = open("1.txt","w", encoding="utf-8")
    f.write("anarana") # 61 0D 0A 61 0D 61 0D 0A 61

    print(type(f))
    f.close()

    f = open("2.txt", "w", encoding="utf-8",newline="n")
    f.write("anara") # 61 0A 61 0D 61
    f.close()

    f = open("3.txt", "w", encoding="utf-8", newline="n")
    print("%snara " % "a",end="n",file=f) # 61 0A 61 0D 61 20 0A
    f.close()
参考
  1. print-lf-with-python-3-to-windows-stdout

  2. Linux、Windows 和 Mac 中的换行符对比

  3. io — Core tools for working with streams — Python 3.10.1 documentation

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/664232.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号