'utf-8' 编解码器无法解码在 Python3.4 中读取文件的字节,但在 Python2.7 中则不能

新手上路,请多包涵

我试图在 python2.7 中读取一个文件,它被完美地读取了。我遇到的问题是当我在 Python3.4 中执行相同的程序然后出现错误:

 'utf-8' codec can't decode byte 0xf2 in position 424: invalid continuation byte'

此外,当我在 Windows 中运行程序时(使用 python3.4),不会出现错误。文件的第一行是: Codi;Codi_lloc_anonim;Nom

我的程序代码是:

 def lectdict(filename,colkey,colvalue):
    f = open(filename,'r')
    D = dict()

    for line in f:
       if line == '\n': continue
       D[line.split(';')[colkey]] = D.get(line.split(';')[colkey],[]) + [line.split(';')[colvalue]]

f.close
return D

Traduccio = lectdict('Noms_departaments_centres.txt',1,2)

原文由 oscarcapote 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 758
2 个回答

在 Python2 中,

 f = open(filename,'r')
for line in f:

从文件中读取行 作为 bytes

在 Python3 中,相同的代码从文件中读取行 _作为字符串_。 Python3 字符串是 Python2 调用的 unicode 对象。这些是根据某种编码解码的字节。 Python3 中的默认编码是 utf-8

错误信息

'utf-8' codec can't decode byte 0xf2 in position 424: invalid continuation byte'

显示 Python3 正在尝试将字节解码为 utf-8 。由于存在错误,该文件显然不包含 utf-8 encoded bytes

要解决此问题,您需要 指定文件的正确编码

 with open(filename, encoding=enc) as f:
    for line in f:

如果您不知道正确的编码,您可以运行这个程序来简单地尝试 Python 已知的所有编码。如果幸运的话,会有一种编码将字节转换为可识别的字符。有时 可能 不止一种编码有效,在这种情况下,您需要仔细检查和比较结果。

 # Python3
import pkgutil
import os
import encodings

def all_encodings():
    modnames = set(
        [modname for importer, modname, ispkg in pkgutil.walk_packages(
            path=[os.path.dirname(encodings.__file__)], prefix='')])
    aliases = set(encodings.aliases.aliases.values())
    return modnames.union(aliases)

filename = '/tmp/test'
encodings = all_encodings()
for enc in encodings:
    try:
        with open(filename, encoding=enc) as f:
            # print the encoding and the first 500 characters
            print(enc, f.read(500))
    except Exception:
        pass

原文由 unutbu 发布,翻译遵循 CC BY-SA 3.0 许可协议

就我而言,我无法更改编码,因为我的文件实际上是 UTF-8 编码的。但是有些行已损坏并导致相同的错误:

 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 7092: invalid continuation byte

我的决定是以 二进制模式 打开文件:

 open(filename, 'rb')

原文由 dyomas 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题