python字典保存至json文件


import os
import json class SaveJson(object): def save_file(self, path, item): # 先將字典對象轉化為可寫入文本的字符串 item = json.dumps(item) try: if not os.path.exists(path): with open(path, "w", encoding='utf-8') as f: f.write(item + ",\n") print("^_^ write success") else: with open(path, "a", encoding='utf-8') as f: f.write(item + ",\n") print("^_^ write success") except Exception as e: print("write error==>", e) if __name__ == '__main__': # 保存的文件名 path = "test1.json" # 案例字典數據 item = {"ID": "1001", "name": "Lattesea", "age": "21", "date": "1998-01-18", "sex": "男"} s = SaveJson() # 測試代碼,循環寫入三行,沒有空行 for i in range(3): s.save_file(path, item)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM