-1

I have a list of objects I defined.

At this moment I am iterating over every element in this list and dumping it into a file. But when I want to recreate the objects I run into problems:

f = open(path, 'w')
for element in ListOfElements:
    json.dump(element.__dict__, f)
f.close()

When trying to recreate an object I do the following:

a = json.JSONDecoder(object_hook = Element.from_json).decode(f.read())

But this is very bad as I must introduce some kind of splitters between the objects in the file. Then it would not be a "true" json anymore. Is there a way to make some kind of

json.dump(ListOfElements, f) #this exact code gives me "... is not JSON serializable"

which would then create a file that is able of recreating the entire list?

Salocin
  • 393
  • 6
  • 17

1 Answers1

1

For storing objects use python in built pickle or cPickle module. These are created specially for storing object.

Check this example from

import pickle

a = {'hello': 'world'}

with open('filename.pickle', 'wb') as handle:
  pickle.dump(a, handle)

with open('filename.pickle', 'rb') as handle:
  b = pickle.load(handle)

print a == b

from How can I use pickle to save a dict?

Community
  • 1
  • 1
sam
  • 1,819
  • 1
  • 18
  • 30