How to handle file non-existence exception in Python3 with open?
阿神
阿神 2017-07-05 10:34:57
0
2
1090
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.

阿神
阿神

闭关修行中......

reply all(2)
我想大声告诉你
fn = input('输入文件名: ')
try:
    with open(fn, 'r') as f:
        pass
except IOError:
    file = open(fn, 'w')
给我你的怀抱
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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template