使用yaml檔案讀取資料

sun_8923發表於2020-11-21

安裝PyYaml模組

pip install PyYaml

讀取yaml檔案

import yaml
with open(path,encoding="utf-8") as op:
            # 忽略yaml不推薦使用的警告
            yaml.warnings({'YAMLLoadWarning': False})
            contents = yaml.load(op)       

如何消除yaml.load()的警告

執行yaml.load()出現警告資訊:
“YAMLLoadWarning:callingyaml.load() without Loader=…”

解決方案():
1、yaml.load(op, Loader=yaml.FullLoader)
2、yaml.warnings({‘YAMLLoadWarning’: False})

yaml練習

# a.yml
- 1     #注意1之前有空格
- 2
- 3
# b.yml
username : user
password : 1234s
verifycode : 0000
data :
  a: !!str 1        #將數字1轉換為字串
  b: 2
  datetime : 2020-09-12
  time : 2020-09-12 01:00:05
import yaml
class Yaml_learn:
    @classmethod
    def get_yaml(cls,path):
        with open(path, encoding="utf-8") as op:
            contents = yaml.load(op,Loader=yaml.FullLoader)
            return contents


if __name__ == '__main__':
    print(Yaml_learn.get_yaml('a.yml'))
    print(Yaml_learn.get_yaml('b.yml'))
    data = Yaml_learn.get_yaml('b.yml')
    print(data['username'])

控制檯輸出

[1, 2, 3]
{'username': 'user', 'password': '1234s', 'verifycode': 0, 'data': {'a': '1', 'b': 2, 'datetime': datetime.date(2020, 9, 12), 'time': datetime.datetime(2020, 9, 12, 1, 0, 5)}}
user

相關文章