赞
踩
在linux
上执行shell
脚本时出现$’\r’:command not found
错误. 在Windows
上打开.sh
文件是能正常显示的,怎么回事?
使用Python
生成的utf-8
格式的文件为什么print
函数设置了end="\n"
还是输出十六进制的0D0A
, 不应该只输出0A
吗?
在Linux
上的Bash shell
脚本文件是严格规定了必须\n
(0A)作为换行符, 因此如果在Windows
上生成的文件以\r\n
作为换行符的话, 执行这个shell
文件时会报错的。
在Python
上使用内置open()
函数来创建一个文本文件对象TextIOBase
超类,而具体的实现子类是<class '_io.TextIOWrapper'>
,可以通过print(type(f))
获得.
这个open()
函数[3]是有坑的,在输出流的描述里,如果newline
不指定,那么任何的\n
会自动转义为系统的默认换行符,也就是在Windows
下生成的文件,遇到\n
写入自动会转换为\r\n
, 也就是十六进制0D0A
, 所以生成的文件放到Linux
上执行就会报上边的错误。解决办法就是在使用open()
时指定newline
参数。
newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. 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 '\r\n', 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.
Windows: \r\n:
Linux: \n
macOS: 可以是\r或者\r\n
Windows
系统下输出文件,并使用winhex
查看文件的十六进制。if __name__ == '__main__': print("hello world") f = open("1.txt","w", encoding="utf-8") f.write("a\na\ra\na") # 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("a\na\ra") # 61 0A 61 0D 61 f.close() f = open("3.txt", "w", encoding="utf-8", newline="\n") print("%s\na\ra " % "a",end="\n",file=f) # 61 0A 61 0D 61 20 0A f.close()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。