Pickle - Load variable if exists or create and save it

Matteo picture Matteo · Nov 10, 2014 · Viewed 16.3k times · Source

Is there a better way to load a variable with pickle if it already exists or create it and dump it if it doesn't?

if os.path.isfile("var.pickle"):
    foo = pickle.load( open( "var.pickle", "rb" ) )
else:
    foo = 3
    pickle.dump( foo, open( "var.pickle", "wb" ) )

Answer

alecxe picture alecxe · Nov 10, 2014

You can follow the EAFP principle and ask for forgiveness:

import pickle

try:
    foo = pickle.load(open("var.pickle", "rb"))
except (OSError, IOError) as e:
    foo = 3
    pickle.dump(foo, open("var.pickle", "wb"))