Editing Pickled Data

I need to save a complex piece of data:

list = ["Animals", {"Cats":4, "Dogs":5}, {"x":[], "y":[]}] 

I planned to save several of these lists in a single file, and I also planned to use the pickle module to save this data. I also want to have access to pickled data and add items to lists in the second dictionary. Therefore, after I print the data and edit, the list may look like this:

 list = ["Animals", {"Cats":4, "Dogs":5}, {"x"=[1, 2, 3], "y":[]}] 

Preferably, I want to save this list (using pickle) in the same file from which I took this piece of data. However, if I simply redistribute the data into the same file (say, I initially saved it in the "File"), in the end I will get two copies of the same list:

 a = open("File", "ab") pickle.dump(list, a) a.close() 

Is there a way to replace the edited list in a file using a pickle instead of adding a second (updated) copy? Or is there another method I should consider to save this data?

+4
source share
2 answers

I think you need a shelf module. It creates a file (uses pickle under the hood) that contains the contents of a variable accessible by key (I think a constant dictionary).

+3
source

You can open the file for writing instead of adding - then the changes will overwrite the previous data. However, this is a problem if more data is stored in this file. If you really want to selectively replace the data in the pickled file, I am afraid that this will not work with the brine. If this is a normal operation, check to see if something like sqlite helps you.

+3
source

All Articles