21.1_python配置文件-conf&ini

一、conf配置文件

1.介绍

  • conf配置文件和ini配置文件读取方式一致,以下以ini为后缀的配置文件为例
  • 配置文件由sections与items组成:
    • sections用来区分不同的配置块
    • items是sections下面的键值对
[common]
web-port = 80
gateway-port = 80
version = 1.0

[log]
console-log-level = info
file-log-level = info
url-log-enable = false

注意:中括号中的内容为sections,每个sections可以有多个items(键值对)

2.使用

  • 读取或更改conf或者ini配置文件,需要导入configparser模块:from configparser import ConfigParser
  • 读取或更改配置前需创建对象和读取文件内容:
    1. config = ConfigParser()
    2. config.read(filename, encoding)

2.1 读取配置

  • config.sections():得到所有的section,并以列表的形式返回
  • config.options(section):得到该section的所有option,并以列表的形式返回
  • config.items(section):得到该section的所有键值对,并以列表的形式返回
  • config[section][option]:读取section中的option的值
  • config.get(section, option):得到该section中option的值,返回类型为str类型
  • config.getint(section, option):得到section中的option的值,返回类型为int类型
  • config.getboolean(section, option):得到section中的option的值,返回类型为bool类型
  • config.getfloat(section, option):得到section中的option的值,返回值为float类型
  • config.has_section(section):检查对应的section是否存在,存在返回True,不存在返回false
  • config.has_option(section, option):检查对应的option是否存在,存在返回True,不存在返回false
  1. config.options(section)config.get(section, option)
    注意:下面的配置文件来自上方的例子
def get_config():
    '''
    获取配置文件内容
    '''
    CONFTEST_FILE_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + r"/conf.ini"
    conf = configparser.ConfigParser()
    conf.read(CONFTEST_FILE_PATH, encoding='utf-8')

    # 获取配置文件内common部分的配置信息
    options = conf.options('common')
    options_dict = {}
    for cmd in options:
        default = conf.get('common', cmd)
        options_dict[cmd] = default

    return options_dict
  1. config.getint(section, option)、config.getboolean(section, option)、config.getfloat(section, option)
  • 配置文件
[common]
web-port = 80
gateway-port = 80
version = 1.0

[log]
console-log-level = info
file-log-level = info
url-log-enable = false
  • 读取配置代码
import os
import configparser

CONFTEST_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), r"test_ini.ini")
conf = configparser.ConfigParser()
conf.read(CONFTEST_FILE_PATH, encoding='utf-8')
print(conf.get("common", "web-port"), type(conf.get("common", "web-port")))
print(conf.getint("common", "web-port"), type(conf.getint("common", "web-port")))
print(conf.get("common", "version"), type(conf.get("common", "version")))
print(conf.getfloat("common", "version"), type(conf.getfloat("common", "version")))
print(conf.get("log", "url-log-enable"), type(conf.get("log", "url-log-enable")))
print(conf.getboolean("log", "url-log-enable"), type(conf.getboolean("log", "url-log-enable")))

输出结果如下:

80 <class 'str'>
80 <class 'int'>
1.0 <class 'str'>
1.0 <class 'float'>
false <class 'str'>
False <class 'bool'>
  1. config.sections()、config.items(section)
  • 配置文件
[common]
web-port = 80
gateway-port = 80
version = 1.0

[log]
console-log-level = info
file-log-level = info
url-log-enable = false
  • 读取配置代码
import os
import configparser

CONFTEST_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), r"test_ini.ini")
conf = configparser.ConfigParser()
conf.read(CONFTEST_FILE_PATH, encoding='utf-8')
print(conf.sections())
print(conf.items("common"))

输出结果如下:

['common', 'log']
[('web-port', '80'), ('gateway-port', '80'), ('version', '1.0')]
  1. config.has_section(section)、config.has_option(section, option)
  • 配置文件
[common]
web-port = 80
gateway-port = 80
version = 1.0

[log]
console-log-level = info
file-log-level = info
url-log-enable = false
  • 读取配置代码
import os
import configparser

CONFTEST_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), r"test_ini.ini")
conf = configparser.ConfigParser()
conf.read(CONFTEST_FILE_PATH, encoding='utf-8')
print(conf.has_section('common'))
print(conf.has_section('envType'))
print(conf.has_option('common', 'version'))
print(conf.has_option('common', 'branch'))

输出结果如下:

True
False
True
False

2.2 更改配置

  • config.add_section(section):添加一个新的section
  • config.set(section, option, value):对section中存在的option是修改,对section中不存在的option是新增
    注意:
    1.如果section不存在,使用set方法就会报错,如果要新增的option的对应section不存在,需要先调用add_section方法,再调用set方法才不报错
    2.使用set方法后不进行写操作,再使用get方法获取的value已经发生变化,只是配置文件保持不变
  • config.write(open(path, "w")):将修改的内容写到配置文件
  • config[section][option]=value:对section中存在的option是修改,对section中不存在的option是新增
  • config.remove_section(section):删除section
  • config.remove_option(section, option):删除section下的option
    注意:使用remove删除section和option,再使用get方法获取的option就会提示option不存在,但是配置文件依旧存在
  1. config.set(section, option, value)、config[section][option]=value、config.write(open(path, "w"))(修改已有配置并同步到配置文件)
  • 配置文件
[common]
web-port = 80
gateway-port = 80
version = 1.0

[log]
console-log-level = info
file-log-level = info
url-log-enable = false
  • 更新配置代码
import os
import configparser

CONFTEST_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), r"test_ini.ini")
conf = configparser.ConfigParser()
conf.read(CONFTEST_FILE_PATH, encoding='utf-8')
conf.set('log', 'console-log-level', 'debug')
print(conf.get('log', 'console-log-level'))
conf["log"]["console-log-level"] = "error"
print(conf.get('log', 'console-log-level'))
conf.write(open(CONFTEST_FILE_PATH, 'w', encoding='utf-8'))

输出结果如下:

debug
error

输出结果后的配置文件如下:

[common]
web-port = 80
gateway-port = 80
version = 1.0

[log]
# 修改配置处
console-log-level = error 
file-log-level = info
url-log-enable = false
  1. config.add_section(section_name)、config.write(open(path, "w"))(新增配置并同步到配置文件)
  • 配置文件
[common]
web-port = 80
gateway-port = 80
version = 1.0

[log]
console-log-level = info
file-log-level = info
url-log-enable = false
  • 新增配置代码
import os
import configparser

CONFTEST_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), r"test_ini.ini")
conf = configparser.ConfigParser()
conf.read(CONFTEST_FILE_PATH, encoding='utf-8')
conf.add_section('envType')
conf.set('envType', 'type', 'uat')
conf.set('common', 'level', 'DAILY_TEST')
conf['common']['branch'] = "master"
conf.write(open(CONFTEST_FILE_PATH, 'w', encoding='utf-8'))

输出结果后的配置文件如下:

[common]
web-port = 80
gateway-port = 80
version = 1.0
# 新增配置处1
level = DAILY_TEST
# 新增配置处2
branch = master

[log]
console-log-level = info
file-log-level = info
url-log-enable = false

# 新增配置处3
[envType]
type = uat
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容