Last active
August 29, 2015 13:57
-
-
Save ekozlowski/9734121 to your computer and use it in GitHub Desktop.
Example of serializing a list using a Python 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 os | |
import pickle | |
FILE_PATH = './my_data.pkl' | |
def load_my_list(): | |
# If the file exists, open it and load our list | |
# from the file at FILE_PATH. | |
if os.path.exists(FILE_PATH): | |
mylist = pickle.load(open(FILE_PATH, 'rb')) | |
else: # otherwise, initialize a new list. | |
mylist = ['A','B','C'] | |
return mylist | |
def save_my_list(mylist): | |
# Write a pickle dump of the list to FILE_PATH. | |
# - A note of caution: this will overwrite whatever was | |
# at that path. | |
pickle.dump(mylist, open(FILE_PATH, 'wb')) | |
if __name__ == "__main__": | |
my_list = load_my_list() | |
print("Loaded my_list - my_list is: {0}".format(my_list)) | |
my_list.append('D') | |
print("Appended 'D' - my_list is now: {0}".format(my_list)) | |
save_my_list(my_list) | |
print("Saved my_list.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment