1 import os 2 import json 3 4 5 class SaveJson(object): 6 7 def save_file(self, path, item): 8 9 # 先将字典对象转化为可写入文本的字符串 10 item = json.dumps(item) 11 12 try: 13 if not os.path.exists(path): 14 with open(path, "w", encoding='utf-8') as f: 15 f.write(item + ", ") 16 print("^_^ write success") 17 else: 18 with open(path, "a", encoding='utf-8') as f: 19 f.write(item + ", ") 20 print("^_^ write success") 21 except Exception as e: 22 print("write error==>", e) 23 24 25 if __name__ == '__main__': 26 # 保存的文件名 27 path = "test1.json" 28 # 案例字典数据 29 item = {"uid": "5bc05421vbjgj34hj9c7d83", "oss_status_code": 200, 30 "url": "http://www.51dev.com//FileUpload/news/202305/20230506212415342.jpg", 31 "updatedAt": "1970-01-18", "createdAt": "1970-01-18", "PID": "5b923c7vbcvbxcswrw342504b", 32 "_id": "5b98d052ed0cbe41","CID":"afdsfgasgfafghdgssdhh"} 33 34 s = SaveJson() 35 36 # 测试代码,循环写入三行,没有空行 37 for i in range(3): 38 s.save_file(path, item)