安裝
Python讀取yaml文件需要安裝第三方庫(kù)pyyaml坚洽,cmd界面輸入命令:pip install pyyaml
safe_dump()
保存為yaml文件
import yaml
import os
info = {"source": 1, "apply_id": 1002411, "send_txt": "關(guān)系邀請(qǐng)", "recv_show": "TA申請(qǐng)成為你的", "send_show": "我申請(qǐng)成為你的",
"relation_type": 12, "uid_list": [123, 454, 678]}
# yaml_path = os.path.dirname(__file__) + "/_account.yaml"
yaml_path = os.path.join(os.getcwd(), "_account.yaml")
print(yaml_path)
with open(yaml_path, "w", encoding="utf-8") as fp:
yaml.safe_dump(info, fp, allow_unicode=True) # 解決中文亂碼
打開(kāi)_account.yaml查看
apply_id: 1002411
recv_show: TA申請(qǐng)成為你的
relation_type: 12
send_show: 我申請(qǐng)成為你的
send_txt: 關(guān)系邀請(qǐng)
source: 1
uid_list:
- 123
- 454
- 678
safe_load()
讀取yaml文件
import yaml
import os
info = {"source": 1, "apply_id": 1002411, "send_txt": "關(guān)系邀請(qǐng)", "recv_show": "TA申請(qǐng)成為你的", "send_show": "我申請(qǐng)成為你的",
"relation_type": 12, "uid_list": [123, 454, 678]}
# yaml_path = os.path.dirname(__file__) + "/_account.yaml"
yaml_path = os.path.join(os.getcwd(), "_account.yaml")
print(yaml_path)
with open(yaml_path, "w", encoding="utf-8") as fp:
yaml.safe_dump(info, fp, allow_unicode=True) # 解決中文亂碼
with open(yaml_path, "r", encoding='utf-8') as f:
fp = yaml.safe_load(f)
print(fp)
輸出如下
F:\study\test\rel_demo\demo_file\_account.yaml
{'apply_id': 1002411, 'recv_show': 'TA申請(qǐng)成為你的', 'relation_type': 12, 'send_show': '我申請(qǐng)成為你的', 'send_txt': '關(guān)系邀請(qǐng)', 'source': 1, 'uid_list': [123, 454, 678]}
解決中文亂碼
yaml.safe_dump(info, fp, allow_unicode=True) # 解決中文亂碼