距开课0天0时0分-9642054秒
阿神2017-07-05 10:34:57 0 2 441
[Python讨论组]举报回复话题 ↕
with open('data.json', 'r') as f: self.cfg = json.load(f)
上述代码段可以读取data.json,
问题是,如果data.json不存在,我该怎样处理?
我在Google搜了一下, 基本都是介绍with的, 无奈本人英文不是太好, 或许错过了些什么...
我的期望是:如果data.json不存在,便创建并写入Json格式的默认参数。
2
0
分享
我想大声告诉你 2017-07-05 10:36:572楼
fn = input('输入文件名: ') try: with open(fn, 'r') as f: pass except IOError: file = open(fn, 'w')
赞 +0添加回复
给我你的怀抱 2017-07-05 10:36:571楼
import os import json name = 'data.json' if not(os.path.exists(name) and os.path.isfile(name)): with open(name, 'w') as f: f.write('["如果data.json不存在,便创建并写入Json格式的默认参数。"]') with open(name, 'r') as f: cfg = json.load(f) print(cfg)
我想大声告诉你 2017-07-05 10:36:572楼
赞 +0添加回复
给我你的怀抱 2017-07-05 10:36:571楼
赞 +0添加回复