Hi I am having some issues with trying to run a very simple program in 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)
The .txt file contains only letters from the latin alphabet. The error I am getting when running in spyder IPython or Python console is:
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)
Now the weird thing is that the program runs just fine from the terminal and both Spyder and the terminal are using the same interpreter so I'm really struggling to see why Spyder is doing this. At the bootom of the screen in Spyder it also explicitly says coding is UTF-8.
The file does contain Unicode characters, the preferred way to open files is it by using the codecs module as it follows:
import codecs
with codecs.open('file', 'r', 'utf-8') as fp:
lines = fp.readlines()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.