![](/img/trans.png)
[英]Writing to file JSON dump from Python 'with open' exception handling
[英]Json File Handling in Python: Writing input to file
這是我試圖以{“ Example1”:“ Example”}格式寫入JSON文件的代碼,我得到一個錯誤,內容為:
db_file.write(json.dump({"Admin": keyPass}, db_file)) TypeError: must be str, not None
對於此代碼:
keyPass = input("Create Admin Password » ")
with codecs.open(os.path.join(PATH), 'w') as db_file:
db_file.write(json.dump({"Admin": keyPass}, db_file))
這是一個很奇怪的部分,它可以在文件中很好地創建它,而我希望如何對其進行格式化是正確的,但是仍然出現上面的錯誤。
有人可以幫我解決這里需要糾正的問題嗎?
json.dump函數的前兩個參數是:
因此,這里發生的是對json.dump的內部調用已成功將JSON編碼的字符串寫入文件,但是隨后您嘗試將其輸出(始終為None)傳遞給文件對象的write函數。
您有兩種選擇:
更新:
這是一些如何做的例子
keyPass = input("Create Admin Password > ")
with open(pathName, 'w') as db_file:
db_file.write(json.dumps({"Admin": keyPass}))
with open(pathName, 'w') as db_file:
json.dump({"Admin": keyPass}, db_file)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.