码迷,mamicode.com
首页 > 编程语言 > 详细

Python不归路_configparser模块

时间:2017-10-31 12:47:05      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:option   ring   python   col   nbsp   string类   返回   int   parse   

 

ConfigParser模块以ConfigParser类为例,其操作基本分为三类:1)初始化;2)读取配置;3)写入配置。

  1. ConfigParser 初始化

使用ConfigParser 首选需要初始化实例,并读取配置文件:

cf = ConfigParser.ConfigParser() cf.read("配置文件名")

  2. 基本的读取配置文件

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

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

-options(section) 得到该section的所有option

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

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

-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。 

  3.基本的写入配置文件

-add_section(section) 添加一个新的section

config[section][option] = values添加一个新的option及值

  4.修改配置文件

-set(section,option,values) 修改option的值

读取配置文件

1 import configparser
2 config = configparser.ConfigParser() #初始化
3 config.read(‘d:\\test.ini‘) #读取ini配置文件
4 print(config.sections()) #读取sectionns
5 print(config.options(‘Manual Scan Configuration‘)) #读取options
6 print(config.items(‘Manual Scan Configuration‘)) #读取options及所对应的值,
7 print(config.get(‘Manual Scan Configuration‘,‘uid‘)) #读取‘uid’的值

写入配置文件

1 import configparser
2 config = configparser.ConfigParser()
3 config[‘info‘] = {}  #创建一个空的section
4 info = config[‘info‘]
5 info[‘age‘] = ‘23‘ #创建一个值为‘23’的option
6 info[‘name‘] = ‘gally‘
7 info[‘hobby‘] = ‘coding,reading‘
8 info[‘HomePage‘] = ‘www.cnblogs.com/gally-jiang‘
9 config.write(open ‘d:\\test.ini‘,‘w‘) #保存写入

修改配置文件

-set(section,option,value)修改值。

config.set(‘info‘,‘age‘,‘25‘)  #修改值

-remove_section(secton)删除section

config.remove_section(‘info‘) #删除section

-remove_option(section,option)删除option

config.remove_option(‘info‘,‘age‘) #删除option

 注意:一旦修改配置文件内容,记得要保存文件。config.write(open(‘d:\\test.int‘,‘w‘))

Python不归路_configparser模块

标签:option   ring   python   col   nbsp   string类   返回   int   parse   

原文地址:http://www.cnblogs.com/gally-jiang/p/7754105.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!