Skip to content

Instantly share code, notes, and snippets.

@adoc
Created March 14, 2015 01:45
Show Gist options
  • Save adoc/a7a4f81205fae0c53fa9 to your computer and use it in GitHub Desktop.
Save adoc/a7a4f81205fae0c53fa9 to your computer and use it in GitHub Desktop.
Python data file with pickle.
class DataFile:
"""Handle a data file using pickle.
"""
def __init__(self, filepath, init_data={}):
"""Initialize or load a pickled data file.
"""
self.__filepath = filepath
self.data = init_data
try:
fp = open(self.__filepath, "rb")
except FileNotFoundError:
fp = open(self.__filepath, "wb")
else:
try:
self.data = pickle.load(fp)
except EOFError:
pass
fp.close()
def save(self):
"""Save changes to disk.
"""
with open(self.__filepath, "wb") as fp:
pickle.dump(self.data, fp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment