Easiest way to persist a data structure to a file in python? Easiest way to persist a data structure to a file in python? python python

Easiest way to persist a data structure to a file in python?


Use the pickle module.

import pickled = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }afile = open(r'C:\d.pkl', 'wb')pickle.dump(d, afile)afile.close()#reload object from filefile2 = open(r'C:\d.pkl', 'rb')new_d = pickle.load(file2)file2.close()#print dictionary object loaded from fileprint new_d


Take your pick: Python Standard Library - Data Persistance. Which one is most appropriate can vary by what your specific needs are.

pickle is probably the simplest and most capable as far as "write an arbitrary object to a file and recover it" goes—it can automatically handle custom classes and circular references.

For the best pickling performance (speed and space), use cPickle at HIGHEST_PROTOCOL.


Try the shelve module which will give you persistent dictionary, for example:

import shelved = { "abc" : [1, 2, 3], "qwerty" : [4,5,6] }shelf = shelve.open('shelf_file')for key in d:    shelf[key] = d[key]shelf.close()....# reopen the shelfshelf = shelve.open('shelf_file')print(shelf) # => {'qwerty': [4, 5, 6], 'abc': [1, 2, 3]}