pickle.dump 사용-TypeError : 바이트가 아닌 str이어야합니다.

python3.3을 사용하고 있으며 간단한 사전을 피클하려고 할 때 암호 오류가 있습니다.

코드는 다음과 같습니다.

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


답변

출력 파일은 이진 모드로 열어야합니다.

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

될 필요가있다:

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

답변

방금 같은 문제가있었습니다. Python 3에서는 이진 모드 ‘wb’, ‘rb’를 지정해야하지만 Python 2x에서는 필요하지 않습니다. Python 2x를 기반으로하는 자습서를 따르면 여기에 있습니다.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")