配置文件:conf
[db]
db_host = 127.0.0.1
db_port = 69
db_user = root
db_pass = root
host_port = 69
test_key = test_val
[concurrent]
thread = 10
processor = 20
configparser_test.py
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File : configparser_test
@IDE :PyCharm
@Author :zhangjun.xue.o
@Date :2019-09-18 15:58
@Desc :
=================================================='''
import configparser
# 初始化示例
config = configparser.ConfigParser()
# 读取配置文件到内存中
config.read("conf")
# 获取所有的section节点
all_sections = config.sections()
print '-- all_sections =', all_sections
# 获取指定section下的options
one_sections_all_options = config.options(all_sections[0])
print '-- one_sections_all_options = ', one_sections_all_options
# 获取指定section下指定option的值
one_option_val = config.get(all_sections[0], one_sections_all_options[0])
print '-- one_option_val = ', one_option_val
# 获取指定section的所有配置信息
one_sections_all_info = config.items(all_sections[0])
print '-- one_sections_all_info = ', one_sections_all_info
# 修改某个option的值,如果不存在则会创建
key, val = 'test_key', 'test_val'
config.set(all_sections[0], key, val)
config.write(open('conf', 'w')) # 将变更写入文件
# 检查section或option是否存在,返回值:bool类型 True or False
has_sections_res = config.has_section(all_sections[0])
print '-- has_sections_res = ', has_sections_res
has_options_res = config.has_option(all_sections[0], one_sections_all_options[0])
print '-- has_options_res = ', has_options_res
not_has_sections_res = config.has_section('name')
print '-- not_has_sections_res = ', not_has_sections_res
no_has_options_res = config.has_option(all_sections[0], 'db_test')
print '-- no_has_options_res = ', no_has_options_res
no_has_section_no_options_res = config.has_option('db_test', 'db_test')
print '-- no_has_section_no_options_res = ', no_has_section_no_options_res
# 添加section 和 option
if not config.has_section("table"): # 检查是否存在section
config.add_section("table")
if not config.has_option("table", "table_name"): # 检查是否存在该option
config.set("table", "table_name", "test_table_name")
config.write(open("conf", "w")) # 将变更写入文件
# 删除section 和 option
config.remove_section("table") # 整个section下的所有内容都将删除
config.write(open("conf", "w")) # 将变更写入文件
'''
读取配置文件和写入配置文件
以下的几行代码只是将文件内容读取到内存中,进过一系列操作之后必须写回文件,才能生效。
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
写回文件的方式如下:(使用configparser的write方法)
config.write(open("ini", "w"))
'''
输出:
-- all_sections = ['db', 'concurrent']
-- one_sections_all_options = ['db_host', 'db_port', 'db_user', 'db_pass', 'host_port', 'test_key']
-- one_option_val = 127.0.0.1
-- one_sections_all_info = [('db_host', '127.0.0.1'), ('db_port', '69'), ('db_user', 'root'), ('db_pass', 'root'), ('host_port', '69'), ('test_key', 'test_val')]
-- has_sections_res = True
-- has_options_res = True
-- not_has_sections_res = False
-- no_has_options_res = False
-- no_has_section_no_options_res = False