简体   繁体   中英

unpickling '_io.BufferedReader' error

Hello everyone I pickled a list of dictionaries to a file using the below code

fd = open(file_name,'ab')
for i in listOFDicts:
    pickle.dump(i,fd)
fd.close()

Then Now I want to load it using the below code

with open(filename, 'rb') as  pickleFile:
    content = pickle.loads(pickleFile)

and I get this error "a bytes-like object is required, not '_io.BufferedReader'"

when I use load() instead of loads()

I get this error

"UnicodeDecodeError: 'ascii' codec can't decode byte 0xc6 in position 0: ordinal not in range(128)"

and if I used pickle.load(filename, encoding='latin1')

I get this error "ModuleNotFoundError: No module named 'bson'"

any help would be really appreciated

Sincerely

I wrote the following code up to show you how to use pickle, edit it to your needs.

import pickle

dict = {0:0, 1:1}

list_of_dict = [dict, dict]

with open("save.pickle", "wb") as f:
    pickle.dump(list_of_dict, f)

del list_of_dict
#print(list_of_dict)
#put below in the other script.
with open("save.pickle", "rb") as f:
    list_of_dict = pickle.load(f)
print(list_of_dict)

This was written in python 3, if you are using python 2, change the following lines:

import pickle

to

import cPickle as pickle

and change the prints appropriately.

The del command was used to delete the variable to save me time from having to write it in 2 scripts. You may ignore that line and then write the remainder in the second script.

Source: Several of my own python scripts used in past and the following: https://wiki.python.org/moin/UsingPickle

EDIT: I've improved the code. Try and use it similarly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM