使用Python创建.JSON文件的代码审查

时间:2017-06-13 12:14:42

标签: python json python-3.x simplejson

我在使用以下代码时遇到问题 它应该最终创建这个“ages.json”文件(因为最初它不存在于目录中 然后,每次运行时,都会增加文件中的年龄),但这种情况并没有发生。

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))

4 个答案:

答案 0 :(得分:1)

尝试

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))

答案 1 :(得分:0)

当您重写文件时,必须先截断它,使用函数truncate()

答案 2 :(得分:0)

你的逻辑不太正确。

我建议先处理不存在,然后加载文件(因为它必须存在)

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"])

答案 3 :(得分:0)

基本上要做的事情还有很长的路要走:

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