pickle.load 不工作
我得到了一个文件,其中包含带有 Windows 用户测试结果的数据结构。他使用 pickle.dump
命令创建了该文件。在 Ubuntu 上,我尝试使用以下程序加载此测试结果:
import pickle
import my_module
f = open('results', 'r')
print pickle.load(f)
f.close()
但我在 pickle 模块内收到错误,没有名为“my_module”的模块。
问题可能是由于文件损坏造成的,或者可能是从 Widows 迁移到 Linux 的原因?
I got a file that contains a data structure with test results from a Windows user. He created this file using the pickle.dump
command. On Ubuntu, I tried to load this test results with the following program:
import pickle
import my_module
f = open('results', 'r')
print pickle.load(f)
f.close()
But I get an error inside pickle module that no module named "my_module".
May the problem be due to corruption in the file, or maybe moving from Widows to Linux is the couse?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题在于 pickle 处理换行符的方式。一些换行符会削弱转储/加载数据中的模块名称。
以二进制模式存储和加载文件可能会有所帮助,但我也遇到了麻烦。经过很长时间的阅读文档和搜索后,我发现 pickle 处理几种不同的“协议”来存储数据,并且由于向后兼容性,它使用最旧的协议:协议 0 - 原始的 ASCII 协议。
用户可以通过在转储文件中存储数据时指定协议关键字来选择现代协议,如下所示:
或者,通过选择可用的最高协议(当前为 2)
协议版本存储在转储文件中,因此 Load() 函数会自动处理它。
问候
The problem lies in pickle's way of handling newline characters. Some of the line feed characters cripple module names in dumped / loaded data.
Storing and loading files in binary mode may help, but I was having trouble with them too. After a long time reading docs and searching I found that pickle handles several different "protocols" for storing data and due to backward compatibility it uses the oldest one: protocol 0 - the original ASCII protocol.
User can select modern protocol by specifing the protocol keyword while storing data in dump file, something like this:
or, by choosing the highest protocol available (currently 2)
Protocol version is stored in dump file, so Load() function handles it automaticaly.
Regards
您应该以二进制模式打开 pickle 文件,特别是当您在不同平台上使用 pickle 时。请参阅此和这个问题以获得解释。
You should open the pickled file in binary mode, especially if you are using pickle on different platforms. See this and this questions for an explanation.