ini

通常由节(Section)、键(key)和值(value)组成;
python内置的configparser标准库,使用read()方法进行解析和读取,最后通过items获取指定节点下的所有键值对。

  1. [local_db]
  2. host = 127.0.0.1
  3. user = root
  4. password = 123456
  5. port = 3306
  6. database = mysql
  1. from configparser import ConfigParser
  2. import os
  3. # 引用ini文件
  4. root_dir = os.path.dirname((os.path.abspath("__file__")))
  5. print(root_dir)
  6. conf = ConfigParser()
  7. conf.read(os.path.join(root_dir, 'test_inii.ini'))
  8. print(dict(conf.items("local_db")))# {'host': '127.0.0.1', 'user': 'root', 'password': '123456', 'port': '3306', 'database': 'mysql'}

JSON

内置的json库,通过load()和loads()方法来解析json

  1. {
  2. "local_db": {
  3. "host": "172.0.0.1",
  4. "user": "root",
  5. "password": "123456",
  6. "port": "3306",
  7. "database": "mysql"
  8. }
  9. }
  1. # 引用json文件
  2. import json
  3. with open(os.path.join(root_dir, 'test_ini.json')) as f:
  4. conf_json = json.load(f)["local_db"]
  5. print(conf_json)# {'host': '172.0.0.1', 'user': 'root', 'password': '123456', 'port': '3306', 'database': 'mysql'}

Toml

toml文件同样通过load()和loads()来进行解析

  1. [mysql]
  2. host = '127.0.0.1'
  3. user = 'root'
  4. password = '123456'
  5. port = '3306'
  6. database = 'mysql'
  7. [mysql.parameters]
  8. pool_size = 5
  9. charset = 'utf8'
  10. [mysql.field]
  11. pandas_col = ['id', 'name', 'age']
  1. # 引用toml文件
  2. import toml
  3. conf_toml = toml.load(os.path.join(root_dir, 'test_toml.toml'))
  4. 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文件

  1. mysql:
  2. host: "127.0.0.1"
  3. user: "root"
  4. password: "123456"
  5. port: 3306
  6. database: "test"
  7. parameter:
  8. pool_size = 5
  9. charset = "utf8"
  10. fields:
  11. pandas_cols:
  12. - id
  13. - name
  14. - age
  15. - date
  1. # 引用yaml文件
  2. import yaml
  3. with open(os.path.join(root_dir, 'test_yaml.yaml')) as f:
  4. conf_yaml = yaml.safe_load(f)
  5. 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']}}}