文章詳情頁
Python3 with open 怎樣處理文件不存在的異常?
問題描述
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. 在windows下安裝docker Toolbox 啟動Docker Quickstart Terminal 失?。?/a>2. java - HashSet<int> 為何有錯誤?3. mysql - 記得以前在哪里看過一個估算時間的網站4. 使用text-shadow可以給圖片加陰影嗎?5. docker start -a dockername 老是卡住,什么情況?6. angular.js - angularjs如何傳遞id給另一個視圖 根據id獲取json數據?7. java - StringBuffer轉成String,可以不同過tostring,而是通過+“”的方式轉換嗎?8. 數據庫無法進入9. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?10. boot2docker無法啟動
排行榜
