Python-pyyaml庫(kù)

安裝

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)  # 解決中文亂碼

打開_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) # 解決中文亂碼

json傳送門

Python-json模塊

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容