ConfigParser模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

1、写入文件

要生成的文件内容为:
[DEFAULT]
compression = yes
serveraliveinterval = 45
compressionlevel = 9
forwordx11 = yes

[bitbucke.org]
user = hg

[topsecret.server.com]
forwardx11 = no
port = 50022

python实现方式:

import configparser

conf = configparser.ConfigParser()

conf["DEFAULT"] = {
'ServerAliveInterval':'45',
'Compression':'yes',
'Compressionlevel':'9'
}
conf['bitbucke.org'] = {
'User':'hg'
}

conf['topsecret.server.com'] = {
'Port' : 50022,
'Forwardx11':'no'
}

#也可以这么写,同上
# topsecret = conf['topsecret.server.com'] #创建一个节点
# topsecret["Port"] = 50022 #节点中添加数据
# topsecret["Forwardxll"] = 'no'

conf['DEFAULT']['Forwordx11'] = 'yes' #在DEFAULT节点添加数据

with open('example.ini','w') as f:
conf.write(f) #写入文件


2、查询操作
import configparser

conf = configparser.ConfigParser()
conf.read('example.ini') #读文件

# print(conf.sections()) #以列表的形式返回节点名称,除了DEFAULT
#
# node = conf.sections()[0] #取出bitbucke.org节点名称
#
# print(conf[node].get('user')) #查询bitbucke.org节点下user对应的数据
#
# print(conf['DEFAULT']['Compression']) #取出DEFAULT节点下Compression对应的数据


print(conf.options('bitbucke.org'))  #取出bitbucke.org节点的所有key值,会把DEFAULT数据一起取出来,以列表形式返回
print(conf.items('bitbucke.org')) #取出bitbucke.org节点的所有key,value值,会把DEFAULT数据一起取出来,以列表形式返回

for key in conf['bitbucke.org']: #遍历bitbucke.org节点的数据,会把DEFAULT数据一起打印出来
print(key,conf['bitbucke.org'][key])

print(conf['bitbucke.org'].get('serveraliveinterval')) #其它节点也可以访问DEFAULT数据,字典中的get方法
print(conf.get('bitbucke.org','serveraliveinterval'))  #该模块下的get方法,功能同上

3、增删改操作

import configparser

conf = configparser.ConfigParser()
conf.read('example.ini') #读文件

# conf.remove_section('bitbucke.org') #删除节点数据
# conf.remove_option('DEFAULT','forwordx11') #删除节点下的serveraliveinterval数据
#
# # with open('example.ini','w') as f:
# # conf.write(f)
# #写入文件也可以这么写
# conf.write(open('example.ini','w'))

conf['bitbucke.org'] = {               #创建节点
'User':'hg'
}

conf.set('topsecret.server.com','forwardx1','yes') #修改topsecret.server.com节点下forwardx11的数据为yes,如果节点下没有该数据则新增数据,节点不存在会报错
conf['topsecret.server.co']['por'] = '1234' #也可以以这种方式修改,如果节点下没有该数据则新增数据,节点不存在会报错
conf.write(open('example.ini','w'))




原文地址:https://www.cnblogs.com/zj-luxj/p/6886142.html