一、configparser模块的作用
configparser适用于生成并操作如下格式的配置文件
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
二、如何用configparser模块生成如上格式的配置文件
导入configparser模块后,生成一个configparser的对象,然后像字典的方式定义配置文件的内容,最后打开一个文件将定义的内容写入文件即可,比如
import configparser config=configparser.ConfigParser() #生成对象 config["DEFAULT"]={ ‘ServerAliveInterval‘: ‘45‘, ‘Compression‘: ‘yes‘, ‘CompressionLevel‘: ‘9‘, ‘ForwardX11‘:‘yes‘ } config["bitbucket.org"]={‘User‘:‘hg‘} #生成配置文件的内容 config[‘topsecret.server.com‘]={‘Host Port‘:‘50022‘,‘ForwardX11‘:‘no‘} with open(‘example.ini‘,‘w‘) as configfile: config.write(configfile) #将配置写入文件
三、从配置文件中获取信息
import configparser config=configparser.ConfigParser() config.read(‘example.ini‘) #读入配置文件 print(config.sections()) #输出所有节点名称 print(‘bytebong.com‘ in config) print(‘bitbucket.org‘ in config) #判断指定节点是否存在 print(config[‘bitbucket.org‘]["user"]) #取值 print(config[‘bitbucket.org‘]) #输出节点名称 for key in config[‘bitbucket.org‘]: #输出节点中每个配置项的名字,如果有DEFAULT则会将DEFAULT的配置项也一起输出 print(key) print(config.options(‘bitbucket.org‘))#作用同上面的for,结果为列表 print(config.items(‘bitbucket.org‘))#输出为列表,元素是每个配置项何其参数的元祖,同样会输出DEFAULT的配置 print(config.get(‘bitbucket.org‘,‘user‘))#获取指定节点中指定配置项的参数,同样可以获取DEFAULT中的配置项参数
四、增删改
import configparser
config = configparser.ConfigParser()
config.read(‘example.ini‘)
config.add_section(‘yuan‘) #创建新节点
config.remove_section(‘bitbucket.org‘) #删除节点
config.remove_option(‘topsecret.server.com‘,"forwardx11") #删除配置项
config.set(‘topsecret.server.com‘,‘k1‘,‘11111‘) #增加配置项
config.set(‘yuan‘,‘k2‘,‘22222‘)
config.write(open(‘new2.ini‘, "w")) #将修改后的配置写入文件
时间: 2024-08-25 11:21:11