search

Home  >  Q&A  >  body text

How to handle file non-existence exception in Python3 with open?

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

The above code snippet can read data.json,

The question is, if data.json does not exist, what should I do?

I searched on Google, and most of them introduced with. Unfortunately, my English is not very good, so I may have missed something...

My expectation is:
If data.json does not exist, create and write the default parameters in Json format.

阿神阿神2703 days ago1078

reply all(2)I'll reply

  • 我想大声告诉你

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

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

    reply
    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)

    reply
    0
  • Cancelreply