source

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

goodcode 2022. 9. 22. 00:22
반응형

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

python 3.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("------------")

피클은 바이너리 프로토콜을 사용하기 때문에 바이너리 파일만 사용할 수 있습니다. 번째 문장에서 설명한 바와 같이, "피클 모듈은 직렬화 및 직렬화를 위한 바이너리 프로토콜을 구현합니다."

언급URL : https://stackoverflow.com/questions/13906623/using-pickle-dump-typeerror-must-be-str-not-bytes

반응형