在Python中使用pickle.dump [英] Usage of pickle.dump in Python

查看:132
本文介绍了在Python中使用pickle.dump的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

这就是我得到的:

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?

推荐答案

问题是您正在以文本模式打开文件.您需要在此处使用二进制文件:

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

这篇关于在Python中使用pickle.dump的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆