Python Pickle to and From File (use as Cache)

Aug 2, 2019

Pickle to file

import picklefilename = ...data = { ... }with open(filename, 'wb') as f:    pickle.dump(data, f)

Pickle from file

with open(filename, 'rb') as f:    data = pickle.load(f)

Use pickle as cache

import osimport picklefilename = ...if not os.path.exists(filename):    print("no cache")    data = ...    with open(filename, 'wb') as f:        pickle.dump(data, f)else:    print("fetch from cache")    with open(filename, 'rb') as f:        data = pickle.load(f)

cPickle

A common pattern in Python 2.x is to have one version of a module implemented in pure Python, with an optional accelerated version implemented as a C extension; for example, pickle and cPickle. This places the burden of importing the accelerated version and falling back on the pure Python version on each user of these modules. In Python 3.0, the accelerated versions are considered implementation details of the pure Python versions. Users should always import the standard version, which attempts to import the accelerated version and falls back to the pure Python version. The pickle / cPickle pair received this treatment. The profile module is on the list for 3.1. The StringIO module has been turned into a class in the io module. - Source

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.