Created
March 14, 2015 01:45
-
-
Save adoc/a7a4f81205fae0c53fa9 to your computer and use it in GitHub Desktop.
Python data file with pickle.
This file contains hidden or 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
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