使用pickle.dump-TypeError:必须为str,而不是字节 [英] Using pickle.dump - TypeError: must be str, not bytes

查看:153
本文介绍了使用pickle.dump-TypeError:必须为str,而不是字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python3.3,并且在尝试腌制一个简单的字典时遇到一个隐秘错误.

I'm using python3.3 and I'm having a cryptic error when trying to pickle a simple dictionary.

这是代码:

import os
import pickle
from pickle import *
os.chdir('c:/Python26/progfiles/')

def storvars(vdict):      
    f = open('varstor.txt','w')
    pickle.dump(vdict,f,)
    f.close()
    return

mydict = {'name':'john','gender':'male','age':'45'}
storvars(mydict)

我得到:

Traceback (most recent call last):
  File "C:/Python26/test18.py", line 31, in <module>
    storvars(mydict)
  File "C:/Python26/test18.py", line 14, in storvars
    pickle.dump(vdict,f,)
TypeError: must be str, not bytes

推荐答案

需要以二进制模式打开输出文件:

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

需要是:

f = open('varstor.txt','wb')

这篇关于使用pickle.dump-TypeError:必须为str,而不是字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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