安装
Python读取yaml文件需要安装第三方库pyyaml,cmd界面输入命令:pip install pyyaml
safe_dump()
保存为yaml文件
import yaml
import os
info = {"source": 1, "apply_id": 1002411, "send_txt": "关系邀请", "recv_show": "TA申请成为你的", "send_show": "我申请成为你的",
"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) # 解决中文乱码
打开_account.yaml查看
apply_id: 1002411
recv_show: TA申请成为你的
relation_type: 12
send_show: 我申请成为你的
send_txt: 关系邀请
source: 1
uid_list:
- 123
- 454
- 678
safe_load()
读取yaml文件
import yaml
import os
info = {"source": 1, "apply_id": 1002411, "send_txt": "关系邀请", "recv_show": "TA申请成为你的", "send_show": "我申请成为你的",
"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申请成为你的', 'relation_type': 12, 'send_show': '我申请成为你的', 'send_txt': '关系邀请', 'source': 1, 'uid_list': [123, 454, 678]}
解决中文乱码
yaml.safe_dump(info, fp, allow_unicode=True) # 解决中文乱码