python中configparser模块读取ini文件

时间:2023-03-09 03:59:58
python中configparser模块读取ini文件

python中configparser模块读取ini文件

ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。

三种创建方法

程序示例:

import configparser

#实例化出来一个类,相当于生成一个空字典
config = configparser.ConfigParser() #创建也很简单,键:值
# 值:键---值
#第一种方法
config['default']={'IP':'192.168.14.2',
'PORT':'6072'
} #第二种方法
config['Custom']={}
config['Custom']['User']='admin'
config['Custom']['Password']='123456'
<br>
#第三种方法
config['define']={}
Config=config['define']
Config['Host']='192.168.14.2'
Config['Port']='611' with open('confile','w') as configfile:
#注意这里,是谁调用write方法,是config对象,不是文件对象
config.write(configfile)

运行结果:

[default]
ip = 192.168.14.2
port = 6072 [Custom]
user = admin
password = 123456 [define]
host = 192.168.14.2
port = 611

增删改查

import configparser
config = configparser.ConfigParser()
#读取配置文件
config.read('confile')
print('获取文件内所有的section:')
print(config.sections()) print('获得指定section下所有option:')
options=config.options('Custom')
print(options) print('---------------------------查')
print('获取指定option下的值:')
value1=config['Custom']['user']
print(value1)
value2=config.get('Custom','user')
print(value2)
# getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。 print('获取指定section下所有的键值对:')
items = config.items('default')
print(items) print('遍历键值对:')
for key in config['default']:
print(key)<br> #下面都会改变文件,所以最后一步都要重新写入配置文件 print('---------------------------增') print('添加section:')
# config.add_section('key1') print('添加键值对:')
# config.set('key1','k1','123456') print('---------------------------改')
#如果需要修改配置文件里面的值,自行打开修改<br>
print('---------------------------删') print('删除section:')
config.remove_section('key1') print('删除键值对:')
config.remove_option('key1','k1') #重新保存
config.write(open('confile','w'))