您好我在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。
答案 0 :(得分:2)
该文件包含Unicode字符,打开文件的首选方法是使用codecs模块,如下所示:
import codecs
with codecs.open('file', 'r', 'utf-8') as fp:
lines = fp.readlines()