ini
通常由节(Section)、键(key)和值(value)组成;
python内置的configparser标准库,使用read()方法进行解析和读取,最后通过items获取指定节点下的所有键值对。
[local_db]
host = 127.0.0.1
user = root
password = 123456
port = 3306
database = mysql
from configparser import ConfigParser
import os
# 引用ini文件
root_dir = os.path.dirname((os.path.abspath("__file__")))
print(root_dir)
conf = ConfigParser()
conf.read(os.path.join(root_dir, 'test_inii.ini'))
print(dict(conf.items("local_db")))# {'host': '127.0.0.1', 'user': 'root', 'password': '123456', 'port': '3306', 'database': 'mysql'}
JSON
内置的json库,通过load()和loads()方法来解析json
{
"local_db": {
"host": "172.0.0.1",
"user": "root",
"password": "123456",
"port": "3306",
"database": "mysql"
}
}
# 引用json文件
import json
with open(os.path.join(root_dir, 'test_ini.json')) as f:
conf_json = json.load(f)["local_db"]
print(conf_json)# {'host': '172.0.0.1', 'user': 'root', 'password': '123456', 'port': '3306', 'database': 'mysql'}
Toml
toml文件同样通过load()和loads()来进行解析
[mysql]
host = '127.0.0.1'
user = 'root'
password = '123456'
port = '3306'
database = 'mysql'
[mysql.parameters]
pool_size = 5
charset = 'utf8'
[mysql.field]
pandas_col = ['id', 'name', 'age']
# 引用toml文件
import toml
conf_toml = toml.load(os.path.join(root_dir, 'test_toml.toml'))
print(conf_toml)#{'mysql': {'host': '127.0.0.1', 'user': 'root', 'password': '123456', 'port': '3306', 'database': 'mysql', 'parameters': {'pool_size': 5, 'charset': 'utf8'}, 'field': {'pandas_col': ['id', 'name', 'age']}}}
Yaml
导入pyyaml库,通过safe_load()来解析yaml文件
mysql:
host: "127.0.0.1"
user: "root"
password: "123456"
port: 3306
database: "test"
parameter:
pool_size = 5
charset = "utf8"
fields:
pandas_cols:
- id
- name
- age
- date
# 引用yaml文件
import yaml
with open(os.path.join(root_dir, 'test_yaml.yaml')) as f:
conf_yaml = yaml.safe_load(f)
print(conf_yaml)#{'mysql': {'host': '127.0.0.1', 'user': 'root', 'password': '123456', 'port': 3306, 'database': 'test', 'parameter': 'pool_size = 5 charset = "utf8"', 'fields': {'pandas_cols': ['id', 'name', 'age', 'date']}}}