Python configparser模块处理ini文件

1.ini文件

#注释1
;注释2

[info]   #节点1
ver = 1.0  #key = value  键值对1
name = peizhiwenjian

[con]    #节点2
color = "yellow"
show = true
title:test  #key:value  键值对2

两种注释,一种节点,两种键值对,构成的就是ini文件 ,里面key,value都是字符串,可以不加双引号

2. configparser模块的使用

import configparser   #专门处理ini格式的文件

con = configparser.ConfigParser()
#打开文件,读取内容
con.read('ini',encoding='utf-8')
print(con,type(con)) # <configparser.ConfigParser object at 0x0000000003439CC0> <class 'configparser.ConfigParser'>
# 获取所有的节点
result = con.sections()
print(result,type(result)) #['info', 'con'] <class 'list'>
# 获取指定节点的key
result = con.options('con')
print(result,type(result)) #['color', 'show', 'title'] <class 'list'>

 3.configparser模块方法

import configparser   #专门处理ini格式的文件
config = configparser.ConfigParser()
config.read('ini',encoding='utf-8')
print(config.get('con','color')) #获取指定节点指定key 的值  字符串 yellow
print(config.getint('info','age'))  #获取指定节点指定key 的值  数字 18
print(config.getfloat('info','ver'))  #获取指定节点指定key 的值  浮点型 1.0
print(config.getboolean('con','show')) #获取指定节点指定key 的值  布尔型 True
print(config.items('con')) #输出指定节点的所有键值对 [('color', 'yellow'), ('show', 'True'), ('title', 'test')]
print(config.sections())  # 输出所有的节点['info', 'con']
print(config.has_section('con')) #判断是否有这个节点 True
# config.add_section('section1') #内存中新增一个节点
# config.write(open('ini','w',encoding='utf-8'))#保存到文件
# config.remove_section('section1') #内存中删除一个节点
# config.write(open('ini','w',encoding='utf-8'))#保存到文件
print(config.has_option('con','show')) #判断这个节点是否有这个key True
# config.set('info','sex','boy') #在指定节点添加键值对,存在就修改键值对
# config.write(open('ini','w',encoding='utf-8'))#保存到文件
# config.remove_option('info','sex') #删除指定节点的键值对
# config.write(open('ini','w',encoding='utf-8'))#保存到文件

 使用的ini

[info]
ver = 1.0
age = 18
name = zhangsan

[con]
color = yellow
show = True
title = test

 

posted @ 2017-04-28 12:07  1916  阅读(313)  评论(0)    收藏  举报