'ascii'编解码器无法解码字节0xe2 - Sublime Text 3

时间:2018-03-13 09:38:17

标签: python-3.x utf-8 ascii sublimetext3

这是我的第一个问题。

我正在运行以下内容:

  • Sublime Text 3
  • OS 10
  • Python 3.6

我正在尝试打开并在Sublime上打印.txt文件。我使用以下代码:

myfile = open("/stanford.txt", "r")
contents = myfile.read()

这是我收到的错误消息:

Traceback (most recent call last):
 File "/Users/me/python/Test1.py", line 11, in <module> 
  contents = myfile.read()
 File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/encodings/ascii.py", line 26, in decode
  return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 173: ordinal not in range(128)
[Finished in 0.1s with exit code 1]

当我使用Python 2.7运行时,上面的两行代码在Sublime Text 3上运行。它也适用于我在终端上运行它们(使用Python3)。但是,当我在IDLE中尝试它们时它们不起作用:当我在Python3中运行Sublime Text 3时,我得到了完全相同的错误消息。

这是我在Sublime Text 3上的构建配置:

{
 "cmd": ["/Library/Frameworks/Python.framework/Versions/3.6/bin/python3", "$file"],
 "selector": "source.python",
 "file_regex": "file \"(...*?)\", line([0-9]+)"
}

我也尝试添加“PYTHONIOENCODING”但仍然出现相同的错误消息:

{
 "cmd": ["/Library/Frameworks/Python.framework/Versions/3.6/bin/python3", "$file"],
 "selector": "source.python",
 "file_regex": "file \"(...*?)\", line([0-9]+)",
 "env": {"PYTHONIOENCODING": "utf8"}
}

(我也尝试使用短划线而不是上面的“utf-8”。相同的错误信息)。

我需要做什么才能让Sublime Text 3读取文件?

谢谢

编辑:我不认为这个问题与另一个问题重复吗?这适用于我的终端,但不适用于Sublime Text 3。

Edit2:我注意到如果我删除文本文件中包含的撇号('),我就可以毫无问题地打开文件了。只有当我将撇号添加回文本文件时才会出现错误。

1 个答案:

答案 0 :(得分:3)

好的,我终于明白了。

我在open函数中添加了以下内容:

, encoding="utf-8")

它有效。我仍然试图找出一种方法,使其在Sublime上成为我的Python3的永久物。