Skip to content

Instantly share code, notes, and snippets.

@ylogx
Created July 21, 2016 12:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ylogx/7088a34e083e77eb5e2574e07de87bb1 to your computer and use it in GitHub Desktop.
Save ylogx/7088a34e083e77eb5e2574e07de87bb1 to your computer and use it in GitHub Desktop.
Load a dataset and cache it for further calls
import numpy as np
import pickle
def load_and_cache(filename):
output = None
cache_dir = '/tmp/my_project_cache/'
os.makedirs(cache_dir, mode=0o744, exist_ok=True)
cache = cache_dir + filename + '.pkl'
if not os.path.exists(cache):
output = np.genfromtxt(filename, dtype=float, delimiter=',') # TODO: Fill your logic
print('Caching {:1} into {:2}'.format(filename, cache))
with open(cache, 'wb') as f:
pickle.dump(output, f)
else:
print('Reading {:1} from cache {:2}'.format(filename, cache))
with open(cache, 'rb') as f:
output = pickle.load(f)
return output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment