Python3——configparser模块
原文链接:https://blog.csdn.net/atlansi/article/details/83243478
官方文档:https://docs.python.org/zh-cn/3.8/library/configparser.html
configparser-翻译过来为:配置文件分析器,通俗点讲就是用于生成一个.ini的配置文件,可以包含一个或多个节(section),每个节可以有多个参数(键值对)
看一下configparser生成的配置文件的格式
1 [DEFAULT] 2 ServerAliveInterval = 45 3 Compression = yes 4 CompressionLevel = 9 5 ForwardX11 = yes 6 7 [bitbucket.org] 8 User = Atlan 9 10 [topsecret.server.com] 11 Port = 50022 12 ForwardX11 = no
现在看一下类似上方的配置文件是如何生成的
1 import configparser #引入模块 2 3 config = configparser.ConfigParser() #类中一个方法 #实例化一个对象 4 5 config["DEFAULT"] = {'ServerAliveInterval': '45', 6 'Compression': 'yes', 7 'CompressionLevel': '9', 8 'ForwardX11':'yes' 9 } #类似于操作字典的形式 10 11 config['bitbucket.org'] = {'User':'Atlan'} #类似于操作字典的形式 12 13 config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'} 14 15 with open('example.ini', 'w') as configfile: 16 17 config.write(configfile) #将对象写入文件
解释一下,操作方式
1 config["DEFAULT"] = {'ServerAliveInterval': '45', 2 'Compression': 'yes', 3 'CompressionLevel': '9', 4 'ForwardX11':'yes' 5 } #类似于操作字典的形式 6 #config后面跟的是一个section的名字,section的段的内容的创建类似于创建字典。类似与字典当然还有别的操作方式啦! 7 config['bitbucket.org'] = {'User':'Atlan'} #类似与最经典的字典操作方式
和字典的操作方式相比,configparser模块的操作方式,无非是在实例化的对象后面跟一个section,在紧跟着设置section的属性(类似字典的形式)
读文件内容
1 import configparser 2 3 config = configparser.ConfigParser() 4 5 #---------------------------查找文件内容,基于字典的形式 6 7 print(config.sections()) # [] 8 9 config.read('example.ini') 10 11 print(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] 12 13 print('bytebong.com' in config) # False 14 print('bitbucket.org' in config) # True 15 16 17 print(config['bitbucket.org']["user"]) # Atlan 18 19 print(config['DEFAULT']['Compression']) #yes 20 21 print(config['topsecret.server.com']['ForwardX11']) #no 22 23 24 print(config['bitbucket.org']) #<Section: bitbucket.org> 25 26 for key in config['bitbucket.org']: # 注意,有default会默认default的键 27 print(key) 28 29 print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键 30 31 print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有键值对 32 33 print(config.get('bitbucket.org','compression')) # yes get方法Section下的key对应的value
修改
1 import configparser 2 3 config = configparser.ConfigParser() 4 5 config.read('example.ini') #读文件 6 7 config.add_section('yuan') #添加section 8 9 10 11 config.remove_section('bitbucket.org') #删除section 12 config.remove_option('topsecret.server.com',"forwardx11") #删除一个配置项 13 14 15 config.set('topsecret.server.com','k1','11111') 16 config.set('yuan','k2','22222') 17 with open('new2.ini','w') as f: 18 config.write(f)
-------------------------------------------------------------

浙公网安备 33010602011771号