介绍python中读取常见配置文件的方式

更新于 2021-11-21


ini类型配置文件

配置文件格式

首先定义一个配置文件如下的格式:

1
2
3
4
5
6
7
# host.ini
[localdb]
host = 127.0.0.1
user = root
password = 123456
port = 3306
database = mysql

[localdb]表示一个分组,下面的变量使用key-value格式

读取配置文件

读取配置文件是利用python内置的configparser标准库,对配置文件进行解析。

1
2
3
4
5
6
7
8
>>> from configparser import ConfigParser  
>>> cfg = ConfigParser()
>>> cfg.read("host.ini")
['/root/host.ini']
>>> cfg.items("localdb")
[('host', '127.0.0.1'), ('user', 'root'), ('password', '123456'), ('port', '3306'), ('database', 'mysql')]
>>> dict(cfg.items("localdb"))
{'host': '127.0.0.1', 'user': 'root', 'password': '123456', 'port': '3306', 'database': 'mysql'}

或者定义一个类,用来读取配置文件:

1
2
3
4
5
6
7
8
9
10
11
12
# getconfig.py
import os
from configparser import ConfigParser


class Getconfig(object):

def getconfig(self, section, key):
conf = ConfigParser()
path = os.path.split(os.path.realpath(__file__))[0] + '/config/host.ini'
conf.read(path)
return conf.get(section, key)

这个类接收两个参数:

  • section为配置文件中的分组的名称,如register
  • key为配置文件中分组下的key名,如title

使用中,只需要实例化这个类,然后传入需要读取的配置即可,例如:

1
2
3
4
import getconfig

config = getconfig.Getconfig()
regist_port = config.getconfig('localdb', 'port')

json格式配置文件

配置文件格式

1
2
3
4
5
6
7
8
9
10
// db.json
{
"localdb":{
"host": "127.0.0.1",
"user": "root",
"password": "123456",
"port": 3306,
"database": "mysql"
}
}

读取配置文件

python中可以直接用json标准库将json解析为字典进行操作:

1
2
3
4
5
6
7
8
9
10
11
12
>>> import json  
>>> from pprint import pprint
>>>
>>> with open('/Users/Bobot/db.json') as j:
... cfg = json.load(j)['localdb']
...
>>> pprint(cfg)
{'database': 'mysql',
'host': '127.0.0.1',
'password': '123456',
'port': 3306,
'user': 'root'}

json格式的配置文件写注释不是很方便,而且如果配置文件嵌套过多容易出现问题。


toml类型配置文件

配置文件格式

1
2
3
4
5
6
7
8
9
10
11
12
13
# config.toml
[mysql]
host = "127.0.0.1"
user = "root"
port = 3306
database = "test"

[mysql.parameters]
pool_size = 5
charset = "utf8"

[mysql.fields]
pandas_cols = [ "id", "name", "age", "date"]

toml有点类似ini格式的配置文件,但是toml支持更多的数据类型,例如数组、时间戳等。

读取配置文件

首先需要安装一个包:

1
$ pip install toml

然后读取toml配置文件,将其转化为一个字典:

1
2
3
4
5
6
7
8
9
10
11
>>> import toml  
>>> import os
>>> from pprint import pprint
>>> cfg = toml.load(os.path.expanduser("~/Desktop/config.toml"))
>>> pprint(cfg)
{'mysql': {'database': 'test',
'fields': {'pandas_cols': ['id', 'name', 'age', 'date']},
'host': '127.0.0.1',
'parameters': {'charset': 'utf8', 'pool_size': 5},
'port': 3306,
'user': 'root'}}

yaml/yml格式配置文件

配置文件格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# config.yaml
mysql:
host: "127.0.0.1"
port: 3306
user: "root"
password: "123456"
database: "test"

parameter:
pool_size: 5
charset: "utf8"

fields:
pandas_cols:
- id
- name
- age
- date

读取配置文件

首先需要安装yaml包:

1
$ pip install yaml

yaml包包含load()safe_load()方法,但是推荐使用safe_load()方法,因为load()方法会带来安全问题,可能会直接运行植入在yaml文件中的攻击命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> import os  
>>> from pprint import pprint
>>>
>>> with open(os.path.expanduser("~/config.yaml"), "r") as config:
... cfg = yaml.safe_load(config)
...
>>> pprint(cfg)
{'mysql': {'database': 'test',
'fields': {'pandas_cols': ['id', 'name', 'age', 'date']},
'host': '127.0.0.1',
'parameter': {'charset': 'utf8', 'pool_size': 5},
'password': '123456',
'port': 3306,
'user': 'root'}}