【发布时间】:2017-11-15 05:13:13
【问题描述】:
以下代码有问题。
它应该最终创建这个“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))
【问题讨论】:
-
不要检查文件是否存在。只需在
try/catch块中阅读即可。您的代码有竞争条件。您还需要了解如何覆盖文件。 -
There's a site specifically for Code Review ,但是不应该存在损坏的代码。
-
很抱歉。这实际上是我第一次提出问题,通常我可以弄清楚,但这不是我的代码它实际上来自一个课堂视频,并且在视频上它对教练来说非常有效,因为我什么也没做,很好在 IDLE 中打印出“No File...”。
标签: python json python-3.x simplejson