简体   繁体   中英

Loading all objects of a dictionary from a pickle file

I have my program setup so it takes user input and creates an object from it. Then the object is stored in a dictionary, which in turn is pickled to a .pkl file. Any new object written to this file uses this code:

def save_object(obj, filename):
    with open(filename, 'ab') as output:
        pickle.dump(obj, output, -1)

Now when ii re-open the program i need to load the entire contents of my dictionary which i attempt to do with this:

self.load_file = open("Obj_file.pkl", 'rb+')
self.employee_dict = pickle.load(self.load_file)
print self.employee_dict

Now from my understanding this will load the first two objects only, and this is actually the outcome im seeing when the code is ran. It just opens the first two objects. How can i load the entire dictionary, this seems like it is rather difficult given the research i've done. Also, its essential to my program that i use a dictionary because objects will be deleted from it and i need order to remain the same after such a process is performed.

You opened your pickle file in append mode ; this writes a new pickle record at the end of the file, leaving your first version at the start.

Then, when you read the pickle from the file when you re-open the program, you only read that very first version.

For your needs, it is far simpler to open the file in write mode, replacing all the contents with the new version of your dictionary each time:

def save_object(obj, filename):
    with open(filename, 'wb') as output:
        pickle.dump(obj, output, -1)

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