返回顶部

Python之configparser模块

Python之configparser模块

加载某种特定格式的配置文件

  • python3: import configparser
  • python2: import ConfigParser
#vi test.ini
[section1]
k1=v1
k2:v2
user=wei
age=22
is_admin=true

[section2]
k1=v1

------
import configparser
config=configparser.ConfigParser()
config.read('test.ini')

#1、获取标题sections
print(config.sections())

#2、获取某一section下所有options
print(config.options('section1'))

#3、获取items,查看标题section1下所有key=value的key,value格式
print(config.items('section1'))

#4、获取指定信息,查看标题section1下的user值为字符串格式
res=config.get('section1','user')
print(res,type(res))

#5、查看标题section1下的age的值为整数格式【数值】
res=int(config.get('section1','age'))
res=config.getint('section1','age')

#6、查看标题section1下的is_admin的值为布尔值
res=config.getboolean('section1','is_admin')

#7、查看标题section1下的age的值为浮点型
res=config.getfloat('section1','age')

#8、删除整个section2
config.remove_section('section2')

#9、删除标题section1下的某个k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2')

#判断是否存在某个标题
print(config.has_section('section1'))

#判断标题section1下是否有user
print(config.has_option('section1',''))

#添加一个标题
config.add_section('wei')

#在标题wei下添加name=egon,age=18的配置
config.set('wei','name','wei')
config.set('wei','age',18) #报错,必须是字符串


#最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg','w'))

>>> import configparser
>>> config=configparser.ConfigParser()
>>> config.read('test.ini')
['test.ini']
>>> print(config.sections())
['section1', 'section2']
>>> print(config.options('section1'))
['k1', 'k2', 'user', 'age']
>>> print(config.items('section1'))
[('k1', 'v1'), ('k2', 'v2'), ('user', 'wei'), ('age', '22')]
>>> res=config.get('section1','user')
>>> print(res,type(res))
wei <class 'str'>
>>> res=int(config.get('section1','age'))
>>> print(res)
22
>>> res=config.getint('section1','age')
>>> print(res)
22
>>> res=config.getboolean('section1','is_admin')
>>> print(res,type(res))
True <class 'bool'>
>>> res=config.getfloat('section1','age')
>>> print (res,type(res))
22.0 <class 'float'>

 

 

posted @ 2022-06-15 15:39  九尾cat  阅读(88)  评论(0编辑  收藏  举报