Python: Accessing YAML values using “dot notation”

前端 未结 6 1392
走了就别回头了
走了就别回头了 2020-12-01 15:17

I\'m using a YAML configuration file. So this is the code to load my config in Python:

import os
import yaml
with open(\'./config.yml\') as file:
    config          


        
6条回答
  •  日久生厌
    2020-12-01 15:43

    I ended up using python-box. This package provides multiple ways to read config files (yaml, csv, json, ...). And not only that, it allows you to pass dict or strings directly:

    from box import Box
    import yaml # Only required for different loaders
    
    # Pass dict directly
    movie_box = Box({ "Robin Hood: Men in Tights": { "imdb stars": 6.7, "length": 104 } })
    
    # Load from yaml file
    # Here it is also possible to use PyYAML arguments, 
    # for example to specify different loaders e.g. SafeLoader or FullLoader
    conf = Box.from_yaml(filename="./config.yaml", Loader=yaml.FullLoader) 
    
    conf.mysql.user.pass
    

    A lot more examples, are available in the Wiki.

提交回复
热议问题