【发布时间】:2017-10-12 21:27:14
【问题描述】:
您好,我在尝试在 Spyder 中运行一个非常简单的程序时遇到了一些问题:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 13 18:51:59 2017
@author: admin
"""
f = open('shark-species.txt')
for line in f:
print(line)
.txt 文件仅包含拉丁字母表中的字母。我在 spyder IPython 或 Python 控制台中运行时遇到的错误是:
Traceback (most recent call last):
File "<ipython-input-5-eccaeae0c773>", line 1, in <module>
runfile('/Users/admin/pybin/LCPWP/Chapter4/sharkspecies.py',
wdir='/Users/admin/pybin/LCPWP/Chapter4')
File "/Users/admin/anaconda/lib/python3.5/site-
packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
execfile(filename, namespace)
File "/Users/admin/anaconda/lib/python3.5/site-
packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/admin/pybin/LCPWP/Chapter4/sharkspecies.py", line 11, in
<module>
for line in f:
File "/Users/admin/anaconda/lib/python3.5/encodings/ascii.py", line 26,
in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position
7869: ordinal not in range(128)
现在奇怪的是程序在终端上运行得很好,而且 Spyder 和终端都使用相同的解释器,所以我真的很难理解为什么 Spyder 会这样做。在 Spyder 的屏幕底部,它还明确表示编码是 UTF-8。
【问题讨论】:
-
该编码用于脚本。
-
是的,我明白,但是 .txt 文件也是 utf-8 编码的,我使用的是 Anaconda 提供的 Python 3.5.2 解释器
-
所以?重要的是默认情况下打开文件的编码是什么,而不是脚本的编码。