简体   繁体   English

Python open()函数在Spyder中不起作用,但在具有相同解释器的终端中起作用

[英]Python open() function not working in Spyder but working in the terminal with the same interpreter

Hi I am having some issues with trying to run a very simple program in Spyder: 嗨,我在尝试在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. .txt文件仅包含拉丁字母中的字母。 The error I am getting when running in spyder IPython or Python console is: 在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)

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. 现在很奇怪的是,程序在终端上运行得很好,并且Spyder和终端都使用相同的解释器,所以我真的很难理解Spyder为什么要这样做。 At the bootom of the screen in Spyder it also explicitly says coding is UTF-8. 在Spyder屏幕的底部,它还明确表示编码为UTF-8。

The file does contain Unicode characters, the preferred way to open files is it by using the codecs module as it follows: 该文件确实包含Unicode字符,打开文件的首选方法是使用编解码器模块,如下所示:

 import codecs

 with codecs.open('file', 'r', 'utf-8') as fp:
      lines = fp.readlines()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM