test.ini文件
[section1]
k1 = v1
k2:v2
user=winnie
age=18
is_admin=true
salary=31
[section2]
k1 = v1
执行文件
import configparser
config = configparser.ConfigParser()
config.read('test.ini')
# 1、获取section
print(config.sections())
# 2、获取某一setion下的所有options
print(config.options('section1'))
# 3、获取items
print(config.items('section1'))
# 4、获取指定的value值
res = config.get('section1', 'user')
print(res, type(res))
res = config.getint('section1', 'age')
print(res)
res = config.getboolean('section1', 'is_admin')
print(res, type(res))
res = config.getfloat('section1', 'salary')
print(res, type(res))
结果:
['section1', 'section2']
['k1', 'k2', 'user', 'age', 'is_admin', 'salary']
[('k1', 'v1'), ('k2', 'v2'), ('user', 'winnie'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]
winnie <class 'str'>
18
True <class 'bool'>
31.0 <class 'float'>