美文网首页
python中四种配置文件

python中四种配置文件

作者: 逍遥_yjz | 来源:发表于2021-06-01 14:52 被阅读0次

常用的配置文件后缀是.ini、.conf、.py,当然还有使用.json、.txt的,推荐使用常用的.ini、.py,配置文件的名字一般是config便于理解和使用。

1. ini文件

ini配置文件,这类配置文件我们使用内置configparser库来使用,它可以实现配置文件的写入、更新、删除、读取等操作非常方便,建议使用这种方式。
新建一个config.ini的配置文件内容如下,编码格式要是 utf-8 以免出错。:

[mysql]
name = admin
host = 255.255.255.0
proxy = 6037
password = 123456
pool = true
time = 3
[test]
ip=127.0.0.1
int=1
float=1.5
bool=True
# 你好
[pic_path]
url = https://www.baidu.com/
path = config/
state = 4
[select]
status = 1

其中[]中的是section节点,该节点下的等式是option即键=值
然后每一行写一个option ,每个选项就是一个option。直接写名字,后面加 " = " 再加上它的值就行,字符串的表示不要加引号,否则引号也会被解析出来。
可以在配置文件中加入注释 ,但是注释必须是单独的一行,且以 “#” 开头。只是每次运行时不会读入注释,只要运行一次,写入文件后,所有的注释都会消失。

# -*- coding: utf-8 -*-

import configparser


config = configparser.ConfigParser()
config.read("Config.ini", encoding="utf-8")

config.sections()  # 获取section节点

config.options('mysql')  # 获取指定section 的options即该节点的所有键

config.get("mysql", "name")  # 获取指定section下的options
config.getint("mysql", "proxy")  # 将获取到值转换为int型
config.getboolean("mysql", "pool")  # 将获取到值转换为bool型
config.getfloat("mysql", "time")  # 将获取到值转换为浮点型

config.items("mysql")  # 获取section的所用配置信息

config.set("mysql", "name", "root")  # 修改db_port的值为69

config.has_section("mysql")  # 是否存在该section
config.has_option("mysql", "password")  # 是否存在该option

config.add_section("redis")  # 添加section节点
config.set("redis", "name", "redis_admin")  # 设置指定section 的options

config.remove_section("redis")  # 整个section下的所有内容都将删除
config.remove_option("mysql", 'time')  # 删除section下的指定options

config.write(open("Config", "w"))  # 保存config
# config.items()返回list,元素为tuple,转换成字典类型
pic_path = dict(config.items("pic_path"))
pic_path['url']
pic_path['path']

2. json文件

config.json文件

{
    "mysql": {
        "host": "127.0.0.1",
        "port": 3306,
        "user": "root",
        "password": "123456",
        "database": "test"
    },
    "pic_path":{
        "url"  : "https://www.baidu.com/",
        "path" : "config/",
        "state": 4,
        "city": "上海"
    }
}

使用python内置的 json 标准库进行解析ini文件。
load() 从json文件中读取json格式数据
loads() 将字符串类型数据转化为json格式数据
dump() 将json格式数据保存到文件
dumps() 将json格式数据保存为字符串类型

# coding:utf-8
import json

json_file = "config/config.json"
db_name = "mysql"

with open(json_file,encoding='utf-8') as f:
    cfg = json.load(f)

print(cfg[db_name])
print(cfg['pic_path'])

3. toml文件

TOML的语法广泛地由key = "value"、[节名]、#注释构成。
支持以下数据类型:字符串、整形、浮点型、布尔型、日期时间、数组和图表。
config.toml文件

[mysql]
   [mysql.config]
   host     = "127.0.0.1"
   user     = "root"
   port     = 3306
   password = "123456"
   database = "test"

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

   [mysql.fields]
   course_cols = ["cno", "cname", "ccredit", "cdept"]

[pic_path]
   [pic_path.status]
   url = "https://www.baidu.com/"
   path = "config/"
   state = 4

使用外部库 toml 解析toml文件。

安装:pip install toml
读取文件

# -*- coding: utf-8 -*-

import toml


toml_file = "config/config.toml"

cfg = toml.load(toml_file)

print(cfg)

4. yaml文件

安装:

pip install pyyaml

YAML是目前最推荐的配置文件格式。优秀的配置文件标准它几乎都有:

容易阅读和修改,支持注释。

支持丰富的数据类型。

不同格式的明确表达。

yaml使用时需要注意:

yaml强制缩进。虽然不规定具体缩进几个空格,但是同一级的内容要保持相同的缩进。

冒号后面一定要加空格, 否则无法解析。

python解析 yaml 可以使用pyyaml库,操作和标准的文件操作非常类似:

得到的data就是解析后的数据,在python当中,它是一个嵌套的字典:

想获取某一项配置,再通过字典的操作获取:
config.yaml文件

mysql:
  config:
    host: "127.0.0.1"
    port: 3306
    user: "root"
    password: ""
    database: "stu_sys"

  parameters:
    pool_size: 5
    charset: "utf8"

  fileds:
    course_cols:
      - cno
      - cname
      - ccredit
      - cdept

读取

# -*- coding: utf-8 -*-

import yaml


yaml_file = "config/config.yaml"

with open(yaml_file, 'r') as f:
    cfg = yaml.safe_load(f)

print(cfg)
  • 容易阅读和修改、最好支持注释。所以 json 不是一种好的格式。

  • 易于解析,支持多数据类型。INI 和 xml 不合适。

  • 不同格式用不同的表达。YAML 和 TOML 做得非常好。

  • 用配置文件,选 YAML 和 TOML。

相关文章

网友评论

      本文标题:python中四种配置文件

      本文链接:https://www.haomeiwen.com/subject/dlvwsltx.html