Python Glossary Русский

all Python 3picklefunction

pickle.dump()

serialization

Writes an object to an open binary file in pickle format — to keep a program's state between runs.

Syntax

pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)

Open the file with 'wb': text mode gives TypeError. What is stored is not code but a reference to it — the module.Class path plus attributes for instances — so lambdas and functions defined inside other functions cannot be saved, and loading needs the same class at the same path. The default protocol is 4, and 5 since Python 3.14; set protocol explicitly for a file that older versions must read. Several dumps into one file mean as many successive loads.

Examples

import pickle
state = {'level': 3, 'items': ['меч', 'щит']}
with open('save.pkl', 'wb') as f:
    pickle.dump(state, f)
with open('save.pkl', 'rb') as f:
    print(pickle.load(f))  # → {'level': 3, 'items': ['меч', 'щит']}
import pickle
with open('save.pkl', 'w') as f:
    try:
        pickle.dump(1, f)
    except TypeError as e:
        print(e)  # → write() argument must be str, not bytes

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy