Skip to content

Instantly share code, notes, and snippets.

@AnshKapoor
Created August 15, 2020 13:08
Show Gist options
  • Save AnshKapoor/a0e7f5e90100c41ee8cf45c84dbb8087 to your computer and use it in GitHub Desktop.
Save AnshKapoor/a0e7f5e90100c41ee8cf45c84dbb8087 to your computer and use it in GitHub Desktop.
This code snippet shows how to handle json with python
# pip install simplejson
import simplejson as json # Importing simplejson with a different name for ease of use
import os
if os.path.isfile("./ages.json") and os.stat("./ages.json").st_size !=0: # Checking if a file exists and size is not zero
old_file = open("./ages.json", "r+")
data = json.loads(old_file.read())
print("Current age is:", data["age"])
data["age"] = data["age"]+1
else:
old_file = open("./ages.json", "w+") # If file does not exist then we create one and dump some data into it
data = {"name": "ansh", "age": 23}
old_file.seek(0) # seeking to starting position of file
old_file.write(json.dumps(data)) # Writing data to file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment