Skip to content

Instantly share code, notes, and snippets.

@ekozlowski
Last active August 29, 2015 13:57
Show Gist options
  • Save ekozlowski/9734121 to your computer and use it in GitHub Desktop.
Save ekozlowski/9734121 to your computer and use it in GitHub Desktop.
Example of serializing a list using a Python pickle.
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