首页  >  问答  >  正文

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

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

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

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

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

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

阿神阿神2568 天前910

全部回复(2)我来回复

  • 我想大声告诉你

    我想大声告诉你2017-07-05 10:36:57

    fn = input('输入文件名: ')
    try:
        with open(fn, 'r') as f:
            pass
    except IOError:
        file = open(fn, 'w')
    

    回复
    0
  • 给我你的怀抱

    给我你的怀抱2017-07-05 10:36:57

    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
  • 取消回复