JSON 和 YAML 的語法簡潔明快,都比較適合作為配置文件昌讲。保存也比較簡單国夜,直接調(diào)用 dump
方法就可以了。
如果輸出的文件中有中文的話短绸,就比較麻煩了车吹,輸出的中文就會(huì)變成 \u9ec4
之類的字符串,手工編輯配置文件的話就比較麻煩了醋闭。那么怎么才能直接在配置文件中直接輸出中文呢窄驹?其實(shí)也很簡單,我們?cè)谡{(diào)用 dump
函數(shù)的時(shí)候证逻,增加一些參數(shù)就可以了乐埠。
JSON
import json
with open('abc.conf','w')as f:
json.dump(config, f, indent=4, ensure_ascii=False)
YAML
import yaml
with open('abc.conf','w')as f:
yaml.dump(self.config, f, default_flow_style=False,
indent=2, allow_unicode=True)