切换到Python 3导致UnicodeDecodeError

3ya*_*uya 27 python encoding python-3.x

我刚刚向Sublime添加了Python3解释器,以下代码停止工作:

for directory in directoryList:
    fileList = os.listdir(directory)
    for filename in fileList:
        filename = os.path.join(directory, filename)
        currentFile = open(filename, 'rt')
        for line in currentFile:               ##Here comes the exception.
            currentLine = line.split(' ')
            for word in currentLine:
                if word.lower() not in bigBagOfWords:
                    bigBagOfWords.append(word.lower())
        currentFile.close()
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

  File "/Users/Kuba/Desktop/DictionaryCreator.py", line 11, in <module>
    for line in currentFile:
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xcc in position 305: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我觉得这很奇怪,因为据我所知,Python3应该支持utf-8无处不在.更重要的是,相同的代码在Python2.7上没有任何问题.我已经阅读了关于添加环境变量的内容PYTHONIOENCODING,但我尝试了它 - 无济于事(但是,在OS X Mavericks中添加环境变量似乎并不那么容易,所以也许我在添加变量时做错了?我修改了/etc/launchd.conf)

Mar*_*ers 62

Python 3 在读取时解码文本文件.默认编码取自locale.getpreferredencoding(False),显然对于您的设置返回'ASCII'.查看open()功能文档:

在文本模式下,如果编码未指定使用的编码是与平台相关的:locale.getpreferredencoding(False)被称为获取当前的本地编码.

您应该使用显式编解码器打开文本文件,而不是依赖于系统设置:

currentFile = open(filename, 'rt', encoding='latin1')
Run Code Online (Sandbox Code Playgroud)

在哪里设置encoding参数以匹配您正在阅读的文件.

Python 3支持UTF-8作为源代码的默认值.

这同样适用于写入可写文本文件; 写入的数据将被编码,如果您依赖系统编码,UnicodeEncodingError除非您明确设置合适的编解码器,否则您可能会遇到异常.

您可能希望阅读Unicode HOWTO中的Python 3和Unicode ,它解释了源代码编码以及读取和写入Unicode数据.

  • @Jixiang:你可以在启动Python之前将你的语言环境设置为UTF-8.但是,无论如何,我发现明确设置编码是明智的.显式优于隐式. (2认同)