-1

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))
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • **DON'T** check if a file exists. Just read it in a `try/catch` block. Your code has a race condition. You also need to read up on how to *overwrite* a file. – Jared Smith Jun 13 '17 at 12:17
  • Possible duplicate of [How to overwrite a file in Python?](https://stackoverflow.com/questions/15491417/how-to-overwrite-a-file-in-python) – Jared Smith Jun 13 '17 at 12:20
  • [There's a site specifically for Code Review](https://codereview.stackexchange.com/tour) , however broken code shouldn't be there. – OneCricketeer Jun 13 '17 at 12:22
  • Sorry about that. This is actually my first time asking a question, usually I can figure it out, but this isn't my code it's actually from a a class video, and on the vid it worked perfectly for the instructor, for me did nothing, well it did print out "No File..." in IDLE. – Stephanie Barnes Jun 13 '17 at 13:48

4 Answers4

2

try this

import simplejson as json
import os

if os.path.isfile("./ages.json") and os.stat("./ages.json").st_size !=0:
    old_file = open("./ages.json", "r+")
    data = json.loads(old_file.read())
    print("current age is", data["age"], "Adding User" )
    data["age"] = data["age"] + 1
    print("New Age is ", data["age"])
else:
    old_file = open("./ages.json", "w+")
    data = {"name": "Nick", "age": 26}
    print("No default file Found Setting default age to ", data["age"])
old_file.seek(0)
old_file.write(json.dumps(data))
Bahlbi
  • 25
  • 6
0

When you rewrite file, it must be truncated before, with function truncate()

RandomB
  • 3,367
  • 19
  • 30
0

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"])
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

That's quite a long way around to do basically:

import json

with open("./ages.json", "a+") as f:  # open the file in append+ mode
    f.seek(0)  # move to the beginning of the file
    # read the file or set the 'default' JSON with default (age - 1) as we'll be updating it
    data = json.loads(f.read() or '{"name": "Helio", "age": 87}')
    data["age"] += 1  # increase the age
    f.seek(0)  # move back to the beginning
    f.truncate()  # truncate the rest
    json.dump(data, f)  # write down the JSON
zwer
  • 24,943
  • 3
  • 48
  • 66