文章详情页
Python3 with open 怎样处理文件不存在的异常?
浏览:72日期:2022-06-26 16:32:36
问题描述
with open(’data.json’, ’r’) as f: self.cfg = json.load(f)
上述代码段可以读取data.json,
问题是,如果data.json不存在,我该怎样处理?
我在Google搜了一下, 基本都是介绍with的, 无奈本人英文不是太好, 或许错过了些什么...
我的期望是:如果data.json不存在,便创建并写入Json格式的默认参数。
问题解答
回答1:fn = input(’输入文件名: ’)try: with open(fn, ’r’) as f:passexcept IOError: file = open(fn, ’w’)回答2:
import osimport jsonname = ’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)
相关文章:
1. python - flask jinjia2 中怎么定义嵌套变量2. javascript - jquery选择的dom元素如何更新?3. python - Django问题 ’WSGIRequest’ object has no attribute ’user’4. .......5. MYSQL 的 SELECT 语句中如何做到判断字段为空6. javascript - URL中有#号如何来获取参数啊? nodejs7. html5 - 使用angular中,图片上传功能中选择多张图片是怎么实现的?有什么好的思路吗?8. javascript - H5页面无缝轮播9. 数据库 - mysql boolean型无法插入true10. centos - apache配置django报错:cannot be loaded as Python modules
排行榜
