Skip to content

Instantly share code, notes, and snippets.

@ekozlowski
Last active August 29, 2015 13:57
Show Gist options
  • Save ekozlowski/9734168 to your computer and use it in GitHub Desktop.
Save ekozlowski/9734168 to your computer and use it in GitHub Desktop.
Example of serializing a list using JSON.
import os
import json
FILE_PATH = './my_data.json'
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 = json.loads(open(FILE_PATH, 'rb').read())
else: # otherwise, initialize a new list.
mylist = ['A','B','C']
return mylist
def save_my_list(mylist):
# Write a JSON dump of the list to FILE_PATH.
# - A note of caution: this will overwrite whatever was
# at that path.
json.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