Python的configparser模块

引见:https://blog.csdn.net/henulwj/article/details/49174355

 

函数常用方法:

读取配置文件:

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

 

 

函数
读取配置文件

  1. read(filename) 直接读取ini文件内容

  2. sections() 得到所有的section,并以列表的形式返回

  3. options(section) 得到该section的所有option

  4. items(section) 得到该section的所有键值对

  5. get(section,option) 得到section中option的值,返回为string类型

  6. getint(section,option) 得到section中option的值,返回为int类型

  7. getfloat(section,option)得到section中option的值,返回为float类型

  8. getboolean(section, option)得到section中option的值,返回为boolean类型


写入配置文件

  1. add_section(section) 添加一个新的section
  2. has_section(section) 判断是否有section
  3. set( section, option, value) 对section中的option进行设置
  4. remove_setion(section)删除一个section
  5. remove_option(section, option)删除section中的option
  6. write(fileobject)将内容写入配置文件。
     

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值