python 如何將字典寫為json文件
發(fā)布日期:2022-01-02 22:21 | 文章來源:gibhub
python 將字典寫為json文件
字典結(jié)構(gòu)如下
res = {
"data":[]
}
temp = {
"name":name,
"cls":cls
}
res["data"].append(temp)
寫為json
具體代碼如下:
json_data = json.dumps(res)
with open('E:/res.json', 'a') as f_six:
f_six.write(json_data)
即可完成需求~~
Python txt文件讀取寫入字典(json、eval)
使用json轉(zhuǎn)換方法
1、字典寫入txt
import json
dic = {
'andy':{
'age': 23,
'city': 'beijing',
'skill': 'python'
},
'william': {
'age': 25,
'city': 'shanghai',
'skill': 'js'
}
}
js = json.dumps(dic)
file = open('test.txt', 'w')
file.write(js)
file.close()
2、讀取txt中的字典
import json
file = open('test.txt', 'r')
js = file.read()
dic = json.loads(js)
print(dic)
file.close()
使用str轉(zhuǎn)換方法
1、字典寫入txt
dic = {
'andy':{
'age': 23,
'city': 'beijing',
'skill': 'python'
},
'william': {
'age': 25,
'city': 'shanghai',
'skill': 'js'
}
}
fw = open("test.txt",'w+')
fw.write(str(dic))#把字典轉(zhuǎn)化為str
fw.close()
2、讀取txt中字典
fr = open("test.txt",'r+')
dic = eval(fr.read())#讀取的str轉(zhuǎn)換為字典
print(dic)
fr.close()
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信