在带有cPi的python 3.7上使用python 2.7代码时出现UnicodeDecodeError

2024-04-24 22:05:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个由“解析的”.csv文件构造的.pkl文件上使用cPickle。解析是使用一个预先构建的python工具箱进行的,这个工具箱最近已经从python2(https://github.com/GEMScienceTools/gmpe-smtk)移植到python3

我使用的代码如下:

from smtk.parsers.esm_flatfile_parser import ESMFlatfileParser
parser=ESMFlatfileParser.autobuild("Database10","Metadata10","C:/Python37/TestX10","C:/Python37/NorthSea_Inc_SA.csv")
import cPickle
sm_database = cPickle.load(open("C:/Python37/TestX10/metadatafile.pkl","r"))

它返回以下错误:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 44: character maps to <undefined>

据我所知,我需要指定.pkl文件的编码以使cPickle工作,但我不知道解析.csv文件生成的文件上的编码是什么,因此我目前无法使用cPickle来执行此操作。你知道吗

我使用sublime文本软件发现它是“十六进制”,但在Python3.7中这不是一种可接受的编码格式,不是吗?你知道吗

如果有人知道如何确定所需的编码格式,或者如何使十六进制编码在Python3.7中可用,他们的帮助将不胜感激。你知道吗

另外,诸如“ESMFlatfileparser”之类的模块是预先构建的工具箱的一部分。考虑到这一点,我是否有可能需要在这个模块中以某种方式改变编码?你知道吗


Tags: 模块文件csvimportparser编码格式工具箱
1条回答
网友
1楼 · 发布于 2024-04-24 22:05:11

代码正在以文本模式('r')打开文件,但应该是二进制模式('rb')。你知道吗

documentationpickle.load(强调矿山):

[The] file can be an on-disk file opened for binary reading, an io.BytesIO object, or any other custom object that meets this interface.

由于文件是以二进制模式打开的,因此不需要向open提供编码参数。可能需要为pickle.load提供一个编码参数。来自同一文档:

Optional keyword arguments are fix_imports, encoding and errors, which are used to control compatibility support for pickle stream generated by Python 2. If fix_imports is true, pickle will try to map the old Python 2 names to the new names used in Python 3. The encoding and errors tell pickle how to decode 8-bit string instances pickled by Python 2; these default to ‘ASCII’ and ‘strict’, respectively. The encoding can be ‘bytes’ to read these 8-bit string instances as bytes objects. Using encoding='latin1' is required for unpickling NumPy arrays and instances of datetime, date and time pickled by Python 2.

这应该可以防止UnicodeDecodeError

sm_database = cPickle.load(open("C:/Python37/TestX10/metadatafile.pkl","rb"))

相关问题 更多 >