python中confIgparser模块学习

 

python中configparser模块学习

 

 

 

 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'

#第三种方法 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)
#下面都会改变文件,所以最后一步都要重新写入配置文件 print('---------------------------增') print('添加section:') # config.add_section('key1') print('添加键值对:') # config.set('key1','k1','123456') print('---------------------------改') #如果需要修改配置文件里面的值,自行打开修改
print('---------------------------删') print('删除section:') config.remove_section('key1') print('删除键值对:') config.remove_option('key1','k1') #重新保存 config.write(open('confile','w'))

  

 

转载于:https://www.cnblogs.com/-wenli/p/10309212.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值