我需要将数据保存并加载到 JSON 文件,我已经这样做了,但我知道我遇到了问题
I need to save and load data to a JSON file, and I already did it, but know I have a problem
我正在使用它来将文件中的信息加载到收据目录中。
receipts = {}
with open("receipts.json","r") as file_receipts:
load_receipts = json.load(file_receipts)
receipts = load_receipts
file_receipts.close()
当我创建了json文件时它可以工作,并且里面有信息......但是当文件没有信息时,程序会崩溃,所以我怎样才能避免程序崩溃该程序是 运行 第一次?
另外当json文件有信息时,它有这样的东西:
{"Josh": {"n_orders": 2, "id0": {"combo_1": {"dish": "Personal Pizza", "drink": "Soda", "order": "French Fries", "price": "8", "id": "combo"}}, "id1": {"soda": {"order": "Soda", "price": "2", "id": "order"}}}, "Mary": {"n_orders": 2, "id0": {"pizza": {"order": "Personal Pizza", "price": "4", "id": "dish"}}, "id1": {"soda": {"order": "Soda", "price": "2", "id": "order"}}}}
使用尝试除外:
import os
receipts = {}
if os.path.exist("receipts.json"):
with open("receipts.json","r") as file_receipts:
try:
load_receipts = json.load(file_receipts)
receipts = load_receipts
except:
pass # error handling
# file_receipts.close() # this is not needed inside "with"
捕捉FileNotFoundError
异常,像这样:
try:
with open("receipts.json","r") as file_receipts:
receipts = json.load(file_receipts)
except FileNotFoundError:
receipts = {}
print("File doesn't exist yet.")
我稍微简化了你的代码,你不需要关闭使用 with
打开的文件,因为当执行离开 with
时它们会自动关闭阻止。
我正在使用它来将文件中的信息加载到收据目录中。
receipts = {}
with open("receipts.json","r") as file_receipts:
load_receipts = json.load(file_receipts)
receipts = load_receipts
file_receipts.close()
当我创建了json文件时它可以工作,并且里面有信息......但是当文件没有信息时,程序会崩溃,所以我怎样才能避免程序崩溃该程序是 运行 第一次?
另外当json文件有信息时,它有这样的东西:
{"Josh": {"n_orders": 2, "id0": {"combo_1": {"dish": "Personal Pizza", "drink": "Soda", "order": "French Fries", "price": "8", "id": "combo"}}, "id1": {"soda": {"order": "Soda", "price": "2", "id": "order"}}}, "Mary": {"n_orders": 2, "id0": {"pizza": {"order": "Personal Pizza", "price": "4", "id": "dish"}}, "id1": {"soda": {"order": "Soda", "price": "2", "id": "order"}}}}
使用尝试除外:
import os
receipts = {}
if os.path.exist("receipts.json"):
with open("receipts.json","r") as file_receipts:
try:
load_receipts = json.load(file_receipts)
receipts = load_receipts
except:
pass # error handling
# file_receipts.close() # this is not needed inside "with"
捕捉FileNotFoundError
异常,像这样:
try:
with open("receipts.json","r") as file_receipts:
receipts = json.load(file_receipts)
except FileNotFoundError:
receipts = {}
print("File doesn't exist yet.")
我稍微简化了你的代码,你不需要关闭使用 with
打开的文件,因为当执行离开 with
时它们会自动关闭阻止。