python 读取和写入yaml配置文件

原文链接

首先需要安装PyYAML模块:

pip install PyYAML

然后就可以读取和写入yaml配置文件了。下面是读取示例:

import yaml

with open('config.yml', 'r') as f:
    config = yaml.safe_load(f)

print(config['database'])

下面是写入示例:

import yaml

config = {
    'database': {
        'host': 'localhost',
        'port': 3306,
        'username': 'root',
        'password': 'password'
    }
}

with open('config.yml', 'w') as f:
    yaml.dump(config, f)

以上代码将会将一个名为config.yml的yaml配置文件读取到一个字典中,并打印出其中名为database的键的值。而写入示例将会将一个包含有数据库连接信息的字典写入到名为config.yml的文件中。

你可能感兴趣的:(python,开发语言,linux)