복붙노트

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

PYTHON

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

해결법

  1. ==============================

    1.출력 파일을 바이너리 모드로 열어야합니다.

    출력 파일을 바이너리 모드로 열어야합니다.

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

    될 필요가있다:

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

    2.그냥 똑같은 문제가있었습니다. 파이썬 3에서는 바이너리 모드 'wb', 'rb'를 지정해야하지만 파이썬 2x에서는 필요하지 않습니다. Python 2x를 기반으로하는 자습서를 따라 가면 여기에 있습니다.

    그냥 똑같은 문제가있었습니다. 파이썬 3에서는 바이너리 모드 'wb', 'rb'를 지정해야하지만 파이썬 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("------------")
    
  3. from https://stackoverflow.com/questions/13906623/using-pickle-dump-typeerror-must-be-str-not-bytes by cc-by-sa and MIT license