从零开始的Linux运维屌丝之路,资源免费分享平台   运维人员首选:简单、易用、高效、安全、稳定、社区活跃的开源软件

36、 configparser模块

发布:蔺要红05-25分类: Python


ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值)。
使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活。 

注意:在python 3 中ConfigParser模块名已更名为configparser

ini文件

 

[DEFAULT]
name = mysql
vsersion = 1
[default]
Name2 = nginx
Name3 = apache
[mysql]
prot = 3306
Max_allowed_packet = 16M
[mysqldump]
prot = 6666
max_allowed_packet = 16M
# -*- coding: UTF-8 -*-
# default和 DEFAULT不同,全局变量必须为大写
import configparser
conf = configparser.ConfigParser()
print(conf.sections())#首先需要打开文件,否则为[]
conf.read("my.ini")
print(conf.sections()) #打印所有的节点、默认不打印DEFAULT
print(conf.default_section) #DEFAULT

#D:\python\python.exe F:/运维笔记/python/模块/configparser模块.py
[]
['default', 'mysql', 'mysqldump']
DEFAULT
# -*- coding: UTF-8 -*-
# default和 DEFAULT不同,全局变量必须为大写
import configparser
conf = configparser.ConfigParser()
conf.read("my.ini")
print(list(conf['default'].keys()))      #打节点default下的key、默认包含DEFAULT的key
print(conf.options("default"))           #打节点default下的key、默认包含DEFAULT的key
print((conf['default']["name2"]))        #nginx
print(list(conf["mysqldump"].items()))   #打印节点myisamchk的kye:value

#D:\python\python.exe F:/运维笔记/python/模块/configparser模块增删改.py
['name2', 'name3', 'name', 'vsersion']
['name2', 'name3', 'name', 'vsersion']
nginx
[('prot', '6666'), ('max_allowed_packet', '16M'), ('name', 'mysql'), ('vsersion', '1')]
# -*- coding: UTF-8 -*-
import configparser
conf = configparser.ConfigParser()
conf.read("my.ini")
for k,v in conf["mysqldump"].items(): #打印kye:value包含DEFAULE
    print(k,v)

#D:\python\python.exe F:/运维笔记/python/模块/configparser模块.py
prot 6666
max_allowed_packet 16M
name mysql
vsersion 1

# -*- coding: UTF-8 -*-
import configparser
conf = configparser.ConfigParser()
conf.read("my.ini")
if "buffer" in conf["mysqldump"]: #判断是否有key
    print("False")
else:
    print("True")
print("mysql" in conf) #判断是否有节点
print("max_allowed_packet" in conf['mysqldump'])
print(conf.has_section('mysql')) #判断是否有节点
print(conf.has_option('mysqldump','max_allowed_packet')) #判断是否有key

#D:\python\python.exe F:/运维笔记/python/模块/configparser模块.py
True
True
True
True
True

增删该
 
# -*- coding: UTF-8 -*-
# -*- coding: UTF-8 -*-
import configparser
conf = configparser.ConfigParser()
conf.read("my.ini")
print(dir(conf))

conf.add_section("mysqld") #添加一个节点
conf["mysqld"]['name']="L" #给节点添加一个key:value
conf["mysqld"]['age']="22"
conf.set('mysqld','k1','a',) #给节点添加一个kye:value
conf.set('mysqld','k2','B',) #mysqld节点必须存在,不存在报错

conf.remove_option('mysql', 'prot')
conf.remove_section('mysqldump')
conf.write(open("new_conf.ini",'w'))#写入到新文件

conf.clear()  # 清空除[DEFAULT]之外所有内容
conf.write(open("new_conf2.ini",'w'))#写入到新文件3


#D:\python\python.exe F:/运维笔记/python/模块/configparser模块增删改.py
['BOOLEAN_STATES', 'NONSPACECRE', 'OPTCRE', 'OPTCRE_NV', 'SECTCRE', '_DEFAULT_INTERPOLATION', '_MutableMapping__marker', '_OPT_NV_TMPL',
 '_OPT_TMPL', '_SECT_TMPL', '__abstractmethods__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', 
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__',
 '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', 
'__setattr__', '__setitem__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', 
'_abc_impl', '_allow_no_value', '_comment_prefixes', '_convert_to_boolean', '_converters', '_defaults', '_delimiters', 
'_dict', '_empty_lines_in_values', '_get', '_get_conv', '_handle_error', '_inline_comment_prefixes', '_interpolation', 
'_join_multiline_values', '_optcre', '_proxies', '_read', '_read_defaults', '_sections', '_strict', '_unify_values', '_validate_value_types',
 '_write_section', 'add_section', 'clear', 'converters', 'default_section', 'defaults', 'get', 'getboolean', 'getfloat', 'getint', 'has_option',
 'has_section', 'items', 'keys', 'options', 'optionxform', 'pop', 'popitem', 'read', 'read_dict', 'read_file', 'read_string',
 'readfp', 'remove_option', 'remove_section', 'sections', 'set', 'setdefault', 'update', 'values', 'write']

修改后的ini文件
 
[DEFAULT]
name = mysql
vsersion = 1

[default]
name2 = nginx
name3 = apache

[mysql]    # prot = 3306 被删除
max_allowed_packet = 16M

[mysqld]  #增加了mysqld节点
name = L  #两种方式增加了mysqld下的key:value
age = 22
k1 = a
k2 = B


另外一个ini文件
 
[DEFAULT]  #只有DEFAULT没有被删除
name = mysql
vsersion = 1

特殊用法
 
# -*- coding:utf-8 -*-
import configparser
conf = configparser.ConfigParser()
conf.read("my.ini")
print(conf.remove_section("DEFAULT")) #删除DEFAULT无效
conf.clear()                           #删除DEFAULT无效
print('DEFAULT' in conf)
#但指定删除和增加修改 [DEFAULT] 里的 keys:value 是可以的
print(conf.remove_option("DEFAULT","name"))
conf.set("DEFAULT","age","22")  #增加一个key
conf.set("DEFAULT","vsersion","2") #修改一个key
print(conf["DEFAULT"]["age"])
print(conf["DEFAULT"]["vsersion"])
print(conf.has_section("DEFAULE")) #可以判断除DEFAULT之外的节点是否存在
print("DEFAULT" in  conf)  #判断DEFAULT使用此方法
conf.write(open("new.ini","w"))

#
D:\python\python.exe F:/运维笔记/python/模块/key:value模块.py
False
True
True
22
2
False
True

XML文件内容
 
[DEFAULT]     #DEFAULT没有被删除、其他的被删掉
vsersion = 2  #1被修改成2
age = 22      #新增的key:value
 
温馨提示如有转载或引用以上内容之必要,敬请将本文链接作为出处标注,如有侵权我会在24小时之内删除!

欢迎使用手机扫描访问本站