osc*_*ote 8 python utf-8 python-3.x
我试图在python2.7中读取一个文件,并且它完美无缺.我遇到的问题是当我在Python3.4中执行相同的程序然后出现错误:
'utf-8' codec can't decode byte 0xf2 in position 424: invalid continuation byte'
Run Code Online (Sandbox Code Playgroud)
此外,当我在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)
Run Code Online (Sandbox Code Playgroud)
unu*_*tbu 16
在Python2中,
f = open(filename,'r')
for line in f:
Run Code Online (Sandbox Code Playgroud)
从文件中读取行作为字节.
在Python3中,相同的代码从文件中读取行作为字符串.Python3字符串是Python2调用的unicode
对象.这些是根据某种编码解码的字节.Python3中的默认编码是utf-8
.
错误消息
'utf-8' codec can't decode byte 0xf2 in position 424: invalid continuation byte'
Run Code Online (Sandbox Code Playgroud)
显示Python3正在尝试将字节解码为utf-8
.由于存在错误,文件显然不包含utf-8
编码字节.
要解决此问题,您需要指定文件的正确编码:
with open(filename, encoding=enc) as f:
for line in f:
Run Code Online (Sandbox Code Playgroud)
如果你不知道正确的编码,你可以运行这个程序来简单地尝试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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8371 次 |
最近记录: |