python之ConfigParser

时间:2024-04-29 16:20:20

以前傻傻的不知道还有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'))