我已经安装了json并在“设置”中检查了“项目解释器”,但仍然无法正常工作。
任何帮助,都会很高兴,谢谢。
代码:
import 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())
print("Current age is", data["age"], "-- adding a year")
print("New age is", data["age"])
else: # if no file then
old_file = open("./ages.json", "w+")
data = {"name": "Nickg", "age": 839}
print("No file ffound, default age will be set to", data["age"])
old_file.seek(0)
old_file.write(json.dumps(data))
我尝试仅导入'json'和简单的json
这是结果:
处理完成,退出代码为0
好吧,所以在第一行中,您已经在前面导入了JSON,并且之前有一个空格(我想您只是在输入问题时错了,而不是代码)
此外,如果将追溯添加到您的请求中,那将是很好的,因为退出代码0仅意味着您遇到了错误
但是我认为当前代码中存在问题,是您使用了json.loads(old_file())
。也许尝试
with open('./ages.json', 'r+') as f:
data = json.loads(f.read())
与写入模式相同
with open('./ages.json', 'w+') as f:
f.write(json.dumps(data))
此外,完成所有操作后,请不要忘记关闭文件f.close()
您可以使用OOP:
class JSONFile:
def __init__(self, filename: str):
self.filename = filename
if not filename.endswith('.json'):
self.filename += '.json'
def write(self, content):
with open(self.filename, 'w') as f:
f.write(str(json.dumps(content)))
f.close()
def read(self):
with open(self.filename, 'r') as f:
a = f.read()
f.close()
return json.loads(a)
def append(self, content):
with open(self.filename, 'a') as f:
f.write(str(json.dumps(content)))
f.close()
效果很好,我检查过
抱歉,如果没有帮助,我是编程新手,可能不正确