Pickling
You want to save the entire contents of a data structure to a file so that it can be read the next time the program is run.
Use the Python pickling feature to dump the data structure to file in a format that can be automatically read back into memory as an equivalent data structure later on.
The following example saves a complex list structure to file:
>>> import pickle >>> mylist = [‘some text’, 123, [4, 5, True]] >>> f = open(‘mylist.pickle’, ‘w’) >>> pickle.dump(mylist, f) >>> f.close() |
To unpickle the contents of the file into a new list, use the following:
>>> f = open(‘mylist.pickle’) >>> other_array = pickle.load(f) >>> f.close() >>> other_array [‘some text’, 123, [4, 5, True]] |
Discussion
Pickling will work on pretty much any data structure you can throw at it. It does not need to be a list.
The file is saved in a text format that is sort of human-readable, but you will not normally need to look at or edit the text file.
See Also
To write things to a file and for a list of file open modes, see Recipe 7.6.