1.python數據與yaml數據切換
yaml文件中的數據讀取出來,並轉換為python數據
#讀取yaml數據,將其轉換為python數據,使用load函數 import yaml with open('data2.yaml','r') as f: res = yaml.load(stream=f,Loader=yaml.FullLoader) print(res)
python數據寫入到yaml文件中
import yaml #數據寫入到yaml文件中,使用dump函數,將python數據轉換為yaml數據,並保存在文件中 with open('data3.yaml','w',encoding='utf-8') as f: yaml.dump(cases,f,allow_unicode=True)#allow_unicode=True在數據中存在中文時,解決編碼問題
2.python數據與json數據轉換
python數據轉換為json數據
import json #python數據轉換為json數據,使用dumps函數 li=[None,False,{'a':'python'}] print(json.dumps(li))
json數據轉換為python數據
import json #json數據轉換為python數據,使用loads函數 jstr='[null, false]' print(json.loads(jstr))
將python數據,寫入json文件
import json
#將python數據,寫入json文件(自動化轉換格式),使用dump函數 data=[None,True,{'a':'hello'}] with open(r'E:\Python\python 41\working\day16\testdata\hello.json','w',encoding='utf-8') as f: json.dump(data,f)
加載json文件,轉換為python對應的數據格式
import json
#加載json文件,轉換為python對應的數據格式,使用load函數 with open(r'E:\Python\python 41\working\day16\testdata\hello.json','r',encoding='utf-8') as f: res=json.load(f) print(res)