I used to use the following functions for saving and recalling a dictionary or list of dictionaries to a file using pickle.
- import pickle
-
-
def import_data(file_name):
-
try:
-
f = open(file_name, "r")
-
except IOError, e:
-
# unable to open file
-
Warning("Default file import error. Reverting to original defaults...")
-
return None
-
-
# file open is successful
-
try:
-
-
dd = pickle.Unpickler(f).load()
-
f.close()
-
# test for a dictionary or list of dictionaries
-
if isinstance(dd, dict):
-
return dd
-
elif isinstance(dd, list):
-
for i, item in enumerate(dd):
-
if not isinstance(item, dict):
-
Warning("**INVALID** List item %s is not a dictionary." % (i))
-
return None
-
# always return one dictionary
-
ddr = {}
-
for d in dd: ddr.update(d)
-
return ddr
-
else:
-
# dd is not a dictionary or list of dictionaries
-
Warning("Invalid imported data type.\nData must be a dictionary or list of dictionaries.")
-
return None
-
-
except:
-
# file is not compatible with Unpickler - close file and warn user
-
f.close()
-
Warning("Invalid defaults file. Reverting to original defaults...")
-
return None
-
-
def export_data(file_name, dd):
-
if check_Defaults_dir(os.path.dirname(file_name)):
-
# directory exists or was created
-
try:
-
f = open(file_name, "w")
-
pickle.Pickler(f).dump(dd)
-
f.close()
-
return True
-
except:
-
Warning("Default values file export error.")
-
return False
-
-
else:
-
# directory did not exist and the user chose 'no' to create directory
-
Warning("The default values file export was aborted")
-
return False