Created
November 11, 2014 10:15
-
-
Save caugner/0993c50c11186e3c5472 to your computer and use it in GitHub Desktop.
Dump/load to/from JSON and Pickle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json, pickle | |
def dump_data(data, path): | |
""" | |
Stores an object in a json or pickle file. | |
""" | |
if path.endswith('.json'): | |
t = 'json' | |
elif path.endswith('.pickle'): | |
t = 'pickle' | |
else: | |
raise ArgumentException("I only store to *.json and *.pickle files.") | |
try: | |
print "Storing data to %s ..." % (path), | |
if t == 'json': | |
json.dump(data, open(path, 'w'), indent=2) | |
elif t == 'pickle': | |
pickle.dump(data, open(path, 'wb')) | |
print "done" | |
except Exception as e: | |
print "FAILED ", e | |
def load_data(path): | |
""" | |
Reads an object from a json or pickle file. | |
""" | |
if path.endswith('.json'): | |
t = 'json' | |
elif path.endswith('.pickle'): | |
t = 'pickle' | |
else: | |
raise ArgumentException("I only read *.json and *.pickle files.") | |
try: | |
print "Reading data from %s... " % (path), | |
if t == 'json': | |
data = json.load(open(path, 'r')) | |
elif t == 'pickle': | |
data = pickle.load(open(path, 'rb')) | |
print "done" | |
return data | |
except Exception as e: | |
print "FAILED ", e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment