27

我正在尝试学习如何pickle在 Python 中使用该模块:

import pickle
x = 123
f = open('data.txt','w')
pickle.dump(x,f)

这是我得到的:

Traceback (most recent call last):
  File "D:\python\test.py", line 5, in <module>
    pickle.dump(x,f)
TypeError: must be str, not bytes

但是,这段代码工作得很好:

import pickle
dump = pickle.dump(123)
print(dump)


我究竟做错了什么?

4

2 回答 2

40

问题是您正在以文本模式打开文件。你需要在这里使用二进制:

>>> f = open('data.txt','w')
>>> pickle.dump(123,f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not bytes
>>> 
>>> f = open('data.txt','wb')
>>> pickle.dump(123,f)
>>> 
于 2012-01-02T17:08:40.127 回答
2

类文件对象的 write 方法,只接受一个字符串参数。pickle 模块中的 dumps 方法自动将参数转换为字符串,而 dump 方法会将对象的 pickle 表示写入打开的文件。由于 123 不是字符串,因此会引发 TypeError 错误。

这在pickle.dump 文档中得到确认。

于 2012-01-02T17:07:21.857 回答