308

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
4

3 に答える 3

502

出力ファイルはバイナリ モードで開く必要があります。

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

する必要があります:

f = open('varstor.txt','wb')
于 2012-12-16T23:56:24.917 に答える
42

同じ問題がありました。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("------------")
于 2018-06-09T16:47:54.630 に答える