Concepts / Alternative Data Formats: JSON and CSV

Alternative Data Formats: JSON and CSV

Persistence does not mean that the original in-memory variable remains alive. It means that enough information has been stored in a file for the object to be reconstructed later.

  • Programming

When Memory Is Not Enough

A Python object can exist in memory while a program is running, but that existence is temporary. When the program ends, the object is no longer available in memory. Data persistence solves this problem by storing a Python object in a file so it can survive program termination. Pickle is the mechanism described in this lesson for moving an object from temporary memory into persistent file storage and later bringing it back.

Python objectin RAMPickle fileon diskProgram endsPython objectrestored in RAMtemporaryunpickle later
What happens to a Python object when the program ends, and what changes when it has been saved to a file?

The Persistence Boundary

RAM and file storage play different roles. An object in RAM is fast to access and modify, but it is volatile: it disappears when the program ends or the computer loses power. A file on disk is persistent: it survives program termination and power loss. Pickle bridges these two forms of storage. It converts the object into data that can be written to a file, and the file can later be used to reconstruct the object in memory.

LocationState of the dataWhat happens after program termination
RAMVolatileThe object disappears from memory
File on diskPersistentThe stored data remains available

The source distinguishes temporary objects in RAM from persistent file storage.

Key point

Persistence does not mean that the original in-memory variable remains alive. It means that enough information has been stored in a file for the object to be reconstructed later.

Saving an Object with Pickle

Pickling is the saving stage. The pickle module analyzes the object's type, structure, and nested values, then serializes that information into a binary format. The resulting bytes are written to a file with pickle.dump(). The file must be opened in write binary mode for this operation.

Python objecttype, structure, valuespickle.dump()serializeBytesbinary formatFilepersistent storageinputconverts towrites
How does a Python object move from memory into a file with pickle.dump()?
  1. 1
    Import the pickle module.
  2. 2
    Create or identify the Python object to save.
  3. 3
    Open a file in write binary mode.
  4. 4
    Pass the object and the file to pickle.dump().
  5. 5
    Close the file after the object has been stored.

Restoring the Original Object

Unpickling is the retrieval stage. pickle.load() reads the bytes from a pickle file, decodes the binary data, and reconstructs the object in memory. The file must be opened in read binary mode. The restored object is identical to the original in type, structure, and values.

Filebinary datapickle.load()deserializePython objecttype, structure, valuesrestoredreadsreconstructs
How does stored binary data become a Python object again with pickle.load()?
  1. 1
    Open the stored file in read binary mode.
  2. 2
    Pass the file to pickle.load().
  3. 3
    Allow pickle to read and decode the bytes.
  4. 4
    Receive the reconstructed Python object in memory.

The Shopping List Cycle

Worked example

Saving, deleting, and restoring a shopping list

Follow what happens when a shopping list is stored in a file, removed from memory, and then retrieved.

  1. 1
    Create

    A shopping list is created as a Python list in memory.

  2. 2
    Pickle

    The file shoplist.data is opened in write binary mode, and pickle.dump() stores the list in it.

  3. 3
    Remove

    The shoplist variable is deleted, so the original variable no longer exists in memory.

  4. 4
    Unpickle

    The same file is opened in read binary mode, and pickle.load() retrieves the stored list.

  5. 5
    Restore

    The retrieved object is a list with the same type, structure, and values as the original.

Result

The shopping list is recovered from the file even though the original shoplist variable was deleted.

Shopping listin memorypickle.dump()shoplist.dataVariable deletednot in memorypickle.load()read fileShopping listin memory againstorethenlaterreconstruct
What sequence of events allows an object to survive program termination and become available later?

What do you think happens?

After the shoplist variable is deleted, can the shopping list still be recovered?

  • No, deletion makes recovery impossible

  • Yes, because the stored file contains the serialized object

  • Only if the original variable is recreated manually

Reveal answer
Answer:

Yes, because the stored file contains the serialized object.

pickle.dump() stored the list in shoplist.data before the variable was deleted. pickle.load() later reads that file and reconstructs the list in memory.

Common Persistence Mistakes

  • Common mistake

    Treating pickle.dump() as if it only writes a text version of the object

    What it looks like

    Assuming the file simply contains the ordinary printed representation of a list

    Why it fails

    Pickling performs serialization. It analyzes the object's type, structure, and nested values and encodes them into a binary format.

    Do this instead

    Think of pickle.dump() as converting the complete object into bytes for storage.

  • Common mistake

    Using the wrong file mode for saving

    What it looks like

    Opening the destination file without write binary mode before calling pickle.dump()

    Why it fails

    The source specifies write binary mode for pickling.

    Do this instead

    Open the file in write binary mode before storing the object.

  • Common mistake

    Using the wrong file mode for loading

    What it looks like

    Opening the stored file without read binary mode before calling pickle.load()

    Why it fails

    The source specifies read binary mode for unpickling.

    Do this instead

    Open the file in read binary mode before retrieving the object.

  • Common mistake

    Believing that deleting the variable also deletes the saved data

    What it looks like

    Assuming that removing shoplist from memory removes the contents of shoplist.data

    Why it fails

    The source example deletes the variable after saving and still restores the list from the file.

    Do this instead

    Separate the in-memory variable from the persistent file that contains its serialized data.

A Reliable Save-and-Restore Routine

Keep the two halves of the process distinct. During saving, start with the object in memory, open a file in write binary mode, and use pickle.dump(). During restoration, start with the stored file, open it in read binary mode, and use pickle.load(). Closing the file after saving is part of the demonstrated cycle. This separation makes it easier to identify whether a problem occurred while writing the persistent representation or while reconstructing the object.

StageStarting pointOperationResultFile mode
PicklingPython object in memorypickle.dump()Bytes stored in a fileWrite binary
UnpicklingBytes in a filepickle.load()Python object in memoryRead binary

Pickling and unpickling reverse the direction of the data movement.

Check Your Understanding

EASY

A program creates a Python object, saves it to a file with pickle.dump(), ends, and starts again later. Describe the file mode, function, and data movement required in each stage.

Hints
  • Saving and retrieving use different binary file modes.
  • pickle.dump() moves an object toward a file.
  • pickle.load() moves stored data back into memory.
MEDIUM

Explain why deleting a variable does not prevent recovery when the object was already pickled to a file.

Hints
  • Compare the variable in RAM with the serialized data on disk.
  • Consider what pickle.load() reads.

Persistence in One View

  1. 1
    Data persistence stores Python objects in files so they survive program termination.
  2. 2
    RAM is volatile, while a file on disk is persistent.
  3. 3
    pickle.dump() serializes an object into bytes and writes those bytes in write binary mode.
  4. 4
    pickle.load() reads the bytes in read binary mode and reconstructs the original object.
  5. 5
    The reconstructed object has the same type, structure, and values as the original.

Key Takeaways

  • Persistence allows data to survive after a program terminates.
  • Pickling moves a Python object from volatile memory into a persistent binary file.
  • Unpickling reads that file and reconstructs the object in memory.
  • Saving uses pickle.dump() with write binary mode; retrieval uses pickle.load() with read binary mode.
  • Deleting the original variable does not remove the serialized data already stored in the file.

More concepts starting with A