pythonjsonpython-3.xsimplejson

Code Review for Creating .JSON file with Python


I'm having trouble with the following code.
It's supposed to eventually create this "ages.json" file (because initially it doesn't exist in the directory.
Then, every time it runs, it increases the age in the file), but that is not happening.

import simplejson as json
import os

# checks if the file exists and if the file is empty
if os.path.isfile("./ages.json") and os.stat("./ages.json").st_size != 0:
    old_file = open("./ages.json", "r+")
    # loads the file as python readable
    data = json.loads(old_file.read())
    print("Current age is", data["age"], "-- adding a year.")
    data["age"] = data["age"] + 1
    print("New age is", data["age"])
#if the file is empty or doesn't exist
else:
    old_file = open("./ages.json", "w+")
    data = {"name": "Helio", "age": 88}
    print("No file Found, setting default age to", data["age"])

# starts at the beginning of the file
old_file.seek(0)
# "dumps" data into a json file
old_file.write(json.dumps(data))

Solution

  • Your logic isn't quite correct.

    I'd suggest handling the non existence first, then load the file regardless (because it must exist then)

    import simplejson as json
    import os
    
    filename = 'ages.json'
    f = None 
    # checks if the file doesn't exists or if the file is empty
    if not os.path.isfile(filename) or os.stat(filename).st_size == 0:
        f = open(filename, "w")
        data = {"name": "Helio", "age": 88}
        print("No file Found, setting default age to", data["age"])
        json.dump(data, f)
    if not f:  # open the file that exists now 
        f = open(filename) 
        data = json.load(f) 
    f.close()  # close the file that was opened in either case 
    
    # Print the data from the file
    print("Current age is", data["age"], "-- adding a year.")
    data["age"] = data["age"] + 1
    print("New age is", data["age"])