【问题标题】:Python open() function not working in Spyder but working in the terminal with the same interpreterPython open() 函数在 Spyder 中不起作用,但在终端中使用相同的解释器工作
【发布时间】: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 解释器
  • 所以?重要的是默认情况下打开文件的编码是什么,而不是脚本的编码。

标签: python file spyder


【解决方案1】:

该文件确实包含 Unicode 字符,打开文件的首选方法是使用 codecs 模块,如下所示:

 import codecs

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

【讨论】:

  • 或 Python 2/3 兼容方式:io.open(...).
  • 我认为您的意思是 codecs.open 是的,谢谢,但是您知道为什么标准打开功能在我的终端中有效,但在 spyder 中无效?
  • 如果您使用的是 Python 3,则不需要编解码器,因为内置的 open 具有相同的功能。
  • 嗨,我使用的是 Python 3,内置的 open 函数没有在 spyder 中打开文件
  • @Someguy:它可以在您的终端上运行,因为它支持 utf-8。见:docs.python.org/3/library/…中的sys.getfilesystemencoding()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-29
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多