首页 >社区问答列表 >Python3 with open 怎样处理文件不存在的异常?

Python3 with open 怎样处理文件不存在的异常?

with open('data.json', 'r') as f:
     self.cfg = json.load(f)

上述代码段可以读取data.json,

问题是,如果data.json不存在,我该怎样处理?

我在Google搜了一下, 基本都是介绍with的, 无奈本人英文不是太好, 或许错过了些什么...

我的期望是:
如果data.json不存在,便创建并写入Json格式的默认参数。

  • 给我你的怀抱
  • 给我你的怀抱    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)

    +0添加回复

  • 回复