文章詳情頁
Python3 with open 怎樣處理文件不存在的異常?
瀏覽:102日期: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. css3 - css before 中文亂碼?2. mysql新建字段時 timestamp NOT NULL DEFAULT ’0000-00-00 00:00:00’ 報錯3. javascript - node服務端渲染的困惑4. css - 求推薦幾款好用的移動端頁面布局調試工具呢?5. javascript - webpack --hot 熱重載無效的問題6. Mysql && Redis 并發問題7. php - 第三方支付平臺在很短時間內多次異步通知,訂單多次確認收款8. mysql - 一個表和多個表是多對多的關系,該怎么設計9. html5 - h5寫的app用的webview,用手機瀏覽器打開不顯示?10. javascript - 百度echarts series數據更新問題
排行榜
