文章详情页
Python3 with open 怎样处理文件不存在的异常?
浏览:128日期: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. javascript - 请教如何获取百度贴吧新增的两个加密参数2. javascript - 使用百度文本编辑器ueditor不显示样式问题3. css3 - 关于css的问题,除了倒数第二个td 其他td的宽度都是15%;因为我表格字段数量不确定4. javascript - 能不能用js给一个div添加一个持续的hover的效果,就像有另一个鼠标一直放在上边?5. css - 使用blur()滤镜为什么有透明的效果6. docker - MySQL 报错:Access denied for user ’xxx’@’localhost’7. javascript - 给某个类添加一个伪类,这个类有click事件,现在我点击伪类也触发了click事件8. 如何用笔记本上的apache做微信开发的服务器9. python的 itchat微信api文档的 itchat.send如何发信息给指定用户?10. javascript - autocomplete ajax怎么配置,求教
排行榜
