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

python之ConfigParser

时间:2017-07-26 11:38:18      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:option   xxx   消失   cti   read   key   获取   int   ons   

以前傻傻的不知道还有configParser这么方便的模块,都是一个个的解析转换……

配置文件xxxxx

# 注释1

注释2

[section1] # 节点

k1 = v1    #

k2:v2       #

 

[section2] # 节点

k1 = v1    #

k2=[‘123‘,‘456‘]

节点必须是用[],节点下面的信息必须使用键值对

使用#和;都可以注释信息

 

1、获取所有节点       

import configparser

 

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding=‘utf-8‘)

ret = config.sections()

print ret

 

2、获取指定节点下所有的键值对     

import configparser

 

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding=‘utf-8‘)

ret = config.items(‘section1‘)

print ret

 

3、获取指定节点下所有的建      

import configparser

 

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding=‘utf-8‘)

ret = config.options(‘section1‘)

print ret

 

4、获取指定节点下指定key的值      

import configparser

 

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding=‘utf-8‘)

v = config.get(‘section1‘, ‘k1‘)

 

5、检查、删除、添加节点     

import configparser

config = configparser.ConfigParser()

config.read(‘xxxxx’, encoding=‘utf-8‘)

# 检查

has_sec = config.has_section(‘section1‘)

print has_sec

 

# 添加节点(只要进行了修改,就必须回写,不然信息不保存)

config.add_section("SEC_1")

config.write(open(‘xxxxx’, ‘w‘))

#文件信息被写之后,注释信息自动消失

 

 #删除section或者option

config.remove_section("SEC_1")

config.write(open(‘xxxxx’, ‘w‘))

python之ConfigParser

标签:option   xxx   消失   cti   read   key   获取   int   ons   

原文地址:http://www.cnblogs.com/hellowcf/p/7238516.html

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