码迷,mamicode.com
首页 > 其他好文 > 详细

configparser模块

时间:2020-05-24 16:37:15      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:lis   浮点型   判断   点列   python   oat   add   config   结果   

configparser --configparser模块中的ConfigParser类用来操作ini类型的配置文件

ini配置文件格式

[Section1 Name]    ;节点
KeyName1=value1    ;参数(键值对)
KeyName2=value2
...
[Section2 Name]
KeyName21=value21
KeyName22=value22

;注释使用(;)

基本使用

config.ini文件:

[Section1 Name]
KeyName1=value1
KeyName2=value2
[Section2 Name]
KeyName21=value21
KeyName22=value22

1、读取

from configparser import ConfigParser
filename = ‘config.ini‘
config.read(filename)

# 获取节点列表
sections_list = config.sections()
print(‘节点列表:\n%s‘% sections_list)

# 获取某一节点下所有的键
optinos_list = config.options(sections_list[0])
print(‘键列表:\n%s‘% optinos_list)

#获取某一节点下所有的键值对
item_list = config.items(sections_list[0])
print(‘%s下的所有键值对列表:\n%s‘% (sections_list[0],item_list))

#获取具体参数键值(某一节点下某一参数的具体值)
val1 = config.get(sections_list[0],optinos_list[0]) 
print(‘%s节点下%s的值为:\n%s‘% (sections_list[0], optinos_list[0], val1))

# config.getint(‘section‘,option‘)  option的值必须为整形
# config.getfloat(‘section‘,option‘)  option的值必须为浮点型
# config.getboolean(‘section‘,option‘)  option的值必须为布尔值
结果:
节点列表:
[‘Section1 Name‘, ‘Section2 Name‘]
键列表:
[‘keyname1‘, ‘keyname2‘]
Section1 Name下的所有键值对列表:
[(‘keyname1‘, ‘value1‘), (‘keyname2‘, ‘value2‘)]
Section1 Name节点下keyname1的值为:
value1

2、增删改

#!/usr/bin/python3
# -*- config:utf-8 -*-
import sys,os
from configparser import ConfigParser

filename = ‘config.ini‘
config = ConfigParser()
config.read(filename)

‘‘‘
增删改
‘‘‘

# 添加一个节点Section3 Name
config.add_section(‘Section3 Name‘)

# 在节点Section3 Name下添加参数
config.set(‘Section3 Name‘, ‘keyname31‘, ‘value21‘)

# 判断节点Section3 Name是否存在
if config.has_section(‘Section3 Name‘):
    print(‘%s节点存在‘% ‘Section3 Name‘)
else:
    print(‘%s节点不存在‘% ‘Section3 Name‘)

# 判断节点Section3 Name下是否存在参数keyname31
if config.has_option(‘Section3 Name‘, ‘keyname31‘):
    print(‘%s节点存在参数%s‘% (‘Section3 Name‘,‘keyname31‘))
else:
    print(‘%s节点不存在参数%s‘% (‘Section3 Name‘,‘keyname31‘))

# 删除Section3 Name节点下的keyname31
config.remove_option(‘Section3 Name‘,‘keyname31‘)

# 删除节点Section3 Name
config.remove_section(‘Section3 Name‘)

# 将修改点写入
config.write(open(filename,‘w‘))
结果:
Section3 Name节点存在
Section3 Name节点存在参数keyname31

configparser模块

标签:lis   浮点型   判断   点列   python   oat   add   config   结果   

原文地址:https://www.cnblogs.com/jingxindeyi/p/12945385.html

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