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