Last active
May 10, 2019 10:54
-
-
Save objarni/8af380de57425ddc0c0fc5348069ecaf to your computer and use it in GitHub Desktop.
A quick and dirty way to persist small amounts of data to disk in Python3
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
import pickle | |
def remember(filepath, change): | |
"""Update and persist simple data to filepath using pickle module. | |
The change callback updates the data read from disk; | |
if the file does not exist None is passed and you are | |
responsible for building the initial data. | |
Example use, to keep track of how many times a script has been run: | |
def increment_and_show_count(): | |
count = remember('/home/objarni/.count', lambda x: 1 if x is None else x + 1) | |
print("Count is: {}".format(count)) | |
""" | |
# Load | |
try: | |
with open(filepath, 'rb') as f: | |
data = pickle.load(f) | |
except (FileNotFoundError, EOFError): | |
data = None | |
# Change | |
data = change(data) | |
# Save | |
with open(filepath, 'wb') as f: | |
pickle.dump(data, f, -1) | |
return data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment