Usage of pickle.dump in Python

走远了吗. 提交于 2019-12-03 08:32:25

问题


I'm trying to learn how to use the pickle module in Python:

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

Here's what I get:

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

However, this code works just fine:

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


What am I doing wrong?


回答1:


The problem is that you're opening the file in text mode. You need to use binary here:

>>> 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)
>>> 



回答2:


The write method for file-like objects, only accept a single string argument. The dumps method in the pickle module automatically casts arguments as strings, whereas the the dump method will write a pickled representation of the object to the open file. Since 123 is not a string it throws the TypeError error.

This is acknowledged in pickle.dump documentation.



来源:https://stackoverflow.com/questions/8703366/usage-of-pickle-dump-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!