函数常用方法:
读取配置文件:
import configparser
read(filename) #读取配置文件,直接读取Ini文件内容
sections() #获取ini文件内所有的section,以列表形式返回{‘logging’,‘mysql’}
options(sections) #获取指定sections下所有options,以列表形式返回['host','port','user','password']
items(actions) #获取指定section下所有的键值对,[('host','127.0.0.1'),('port','3306'),('user','root'),('password','123456')]
get(section,option) #获取section中option的值,返回为string类型
getint(section,option) #返回int类型
getfloat(section,option) #返回float类型
getboolean(section,option) #返回boolen类型
#举例如下
配置文件ini如下:
[logging]
level = 20
path = localhost
server =[mysql]
host=127.0.0.1
port=3306
user=root
password=123456
代码如下:
import configparser
from until.file_system import get_init_path #导入自定义模块的方法
conf = configparser.ConfigParser()
file_path = get_init_path() #
print('file_path :',file_path)
conf.read(file_path)
sections = conf.sections()
print('获取配置文件所有的section', sections)
options = conf.options('mysql')
print('获取指定section下所有option', options)
items = conf.items('mysql')
print('获取指定section下所有的键值对', items)
value = conf.get('mysql', 'host')
print('获取指定的section下的option', type(value), value)
结果: file_path : /Users/xxx/Desktop/xxx/xxx/xxx.ini 获取配置文件所有的section ['logging', 'mysql'] 获取指定section下所有option ['host', 'port', 'user', 'password'] 获取指定section下所有的键值对 [('host', '127.0.0.1'), ('port', '3306'), ('user', 'root'), ('password', '123456')] 获取指定的section下的option <class 'str'> 127.0.0.1
函数
读取配置文件
-
read(filename) 直接读取ini文件内容
-
sections() 得到所有的section,并以列表的形式返回
-
options(section) 得到该section的所有option
-
items(section) 得到该section的所有键值对
-
get(section,option) 得到section中option的值,返回为string类型
-
getint(section,option) 得到section中option的值,返回为int类型
-
getfloat(section,option)得到section中option的值,返回为float类型
-
getboolean(section, option)得到section中option的值,返回为boolean类型
写入配置文件
- add_section(section) 添加一个新的section
- has_section(section) 判断是否有section
- set( section, option, value) 对section中的option进行设置
- remove_setion(section)删除一个section
- remove_option(section, option)删除section中的option
- write(fileobject)将内容写入配置文件。