Question 7.9: Pickling You want to save the entire contents of a data stru......

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.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 7.14

Verified Answer:

Import sys and use its argv property, as shown in ...
Question: 7.15

Verified Answer:

Python has a library for the Simple Mail Transfer ...
Question: 7.13

Verified Answer:

Python has an extensive library for making HTTP re...
Question: 7.12

Verified Answer:

Use the random library: >>> import ran...
Question: 7.16

Verified Answer:

Use the bottle Python library to run a pure Python...
Question: 7.11

Verified Answer:

Use the import command: import random Discus...
Question: 7.8

Verified Answer:

To read a file’s contents, you need to use the fil...
Question: 7.7

Verified Answer:

Use the open, write, and close functions to open a...
Question: 7.4

Verified Answer:

Define a class and provide it with the member vari...