Skip to content

Instantly share code, notes, and snippets.

@SourabhSNath
Last active March 2, 2022 10:21
Show Gist options
  • Save SourabhSNath/4af1e6de15cd659adc57a6c0b3c808ee to your computer and use it in GitHub Desktop.
Save SourabhSNath/4af1e6de15cd659adc57a6c0b3c808ee to your computer and use it in GitHub Desktop.
To append new data to json file in python.
import json
if file_exists(file_name):
self.data = import_data_from_json(file_name)
self.data.append(dict_data)
export_data_to_json(file_name, self.data)
else:
# Create new json file if it doesn't exist. Put the data in an array.
export_data_to_json(file_name, [dict_data])
def export_data_to_json(folder_path, data):
json_data = json.dumps(data, indent=4)
with open(folder_path, "w") as f:
f.write(json_data)
def import_data_from_json(json_file: str):
with open(json_file, "r") as f:
data = json.load(f)
return data
def file_exists(path):
return os.path.isfile(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment