使用 Python 创建 .JSON 文件的代码审查
Code Review for Creating .JSON file with Python
我在使用以下代码时遇到问题。
它应该最终创建这个 "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))
当你重写文件时,它必须在之前被截断,函数truncate()
你的逻辑不太正确。
我建议先处理不存在的问题,然后再加载文件(因为它必须存在)
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"])
基本上要做到这一点还有很长的路要走:
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
试试这个
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))
我在使用以下代码时遇到问题。
它应该最终创建这个 "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))
当你重写文件时,它必须在之前被截断,函数truncate()
你的逻辑不太正确。
我建议先处理不存在的问题,然后再加载文件(因为它必须存在)
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"])
基本上要做到这一点还有很长的路要走:
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
试试这个
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))