python将字典写入json文件中
生活随笔
收集整理的這篇文章主要介紹了
python将字典写入json文件中
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import json
with open(r"E:\tianchi_learning\demo_project\train.json", "w") as f2:# dic1就是一個字典js = json.dumps(dic1)f2.write(js)
下面是在實際工作中用到的:
假設存在一個train.json文件, 里面包含三萬張圖片的信息。而我只想要其中的一千張圖片的信息
import json import os# 1.sub_train_path是一個文件夾,里面是我們想要的一千張圖片 sub_train_path = r"E:\tianchi_learning\project1_street_string_classify\datasets\mchar_train\test_img" # 2.創建一個空字典 dic1 = {} # 3.這個json文件就是包含幾萬張圖片的信息 with open(r'E:\tianchi_learning\project1_street_string_classify\datasets\train.json') as f1:json_data = json.load(f1)for img_name in os.listdir(sub_train_path):dic1[img_name] = json_data[img_name]# 4.這個json文件呢是我們最后想要得到的一千張圖片的信息的json文件 with open(r"E:\tianchi_learning\demo_project\sub_train.json", "w") as f2:js = json.dumps(dic1)f2.write(js)總結
以上是生活随笔為你收集整理的python将字典写入json文件中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python快速获取多个列表的所有组合形
- 下一篇: python装饰器简单理解的小demo