Skip to content

Instantly share code, notes, and snippets.

@tsaylor
Last active January 6, 2016 15:38
Show Gist options
  • Save tsaylor/ecbc0d46884e67b06a8a to your computer and use it in GitHub Desktop.
Save tsaylor/ecbc0d46884e67b06a8a to your computer and use it in GitHub Desktop.
Append a value to a json file in place on disk.
import datetime
import json
import os
outfile_name = "data-{}.json".format(datetime.date.today().isoformat())
if os.path.exists(outfile_name):
append_to_json_file(outfile_name, data) # get `data` from somewhere
else:
with open(outfile_name, 'w') as f:
json.dump([data], f, sort_keys=True)
def append_to_json_file(filename, data):
"""Append a value to a json file in place on disk.
Assumes it's appending an object to an array."""
outfile = open(filename, 'rb+') # binary mode is required for the seek operation
last_char_idx = 0
endchar = None
while endchar != b']':
# this loop finds the last json character, skipping over whitespace
last_char_idx -= 1
outfile.seek(last_char_idx, 2)
endchar = outfile.read(1)
outfile.seek(last_char_idx, 2)
outfile.write(',\n {}'.format(json.dumps(data, sort_keys=True)).encode('UTF-8'))
outfile.write(endchar)
outfile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment