Sym*_*nen 1 python linux windows text-files python-3.x
有人能告诉我为什么相同的代码在Linux上正常工作但它不在Windows上吗?
在每个操作系统上执行以下代码:
print("Output :" + open("data.txt", "r").read())
Run Code Online (Sandbox Code Playgroud)
在Windows上出现错误:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
但在Linux上一切正常:
Output :???
Run Code Online (Sandbox Code Playgroud)
问题出在哪儿 ?
我想你的文件是UTF-8,这是Linux上的默认编码,但不是Windows上的默认编码.如果未指定,则使用默认编码.
考虑明确传递编码:
open("data.txt", "r", encoding="utf-8")
Run Code Online (Sandbox Code Playgroud)
(请注意,这是Python 2和Python 3以不同方式处理事物的地方.使用Python 2,您将获得原始字节,就像您"rb"在Python 3中指定的那样.)