configparser模塊簡介
該模塊適用於配置文件的格式與windows ini文件類似,可以包含一個或多個節(section),每個節可以有多個參數(鍵=值)。節與java原先的配置文件相同的格式
看一下configparser生成的配置文件的格式
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = Atlan [topsecret.server.com] Port = 50022 ForwardX11 = no
現在看一下類似上方的配置文件是如何生成的
import configparser #引入模塊 config = configparser.ConfigParser() #類中一個方法 #實例化一個對象 config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' } #類似於操作字典的形式 config['bitbucket.org'] = {'User':'Atlan'} #類似於操作字典的形式 config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'} with open('example.ini', 'w') as configfile: config.write(configfile) #將對象寫入文件
解釋一下,操作方式
config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' } #類似於操作字典的形式 #config后面跟的是一個section的名字,section的段的內容的創建類似於創建字典。類似與字典當然還有別的操作方式啦! config['bitbucket.org'] = {'User':'Atlan'} #類似與最經典的字典操作方式
和字典的操作方式相比,configparser模塊的操作方式,無非是在實例化的對象后面,跟一個section,在緊跟着設置section的屬性(類似字典的形式)
讀取文件內容
import configparser config = configparser.ConfigParser() #---------------------------查找文件內容,基於字典的形式 print(config.sections()) # [] config.read('example.ini') print(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] print('bytebong.com' in config) # False print('bitbucket.org' in config) # True print(config['bitbucket.org']["user"]) # Atlan print(config['DEFAULT']['Compression']) #yes print(config['topsecret.server.com']['ForwardX11']) #no print(config['bitbucket.org']) #<Section: bitbucket.org> for key in config['bitbucket.org']: # 注意,有default會默認default的鍵 print(key) print(config.options('bitbucket.org')) # 同for循環,找到'bitbucket.org'下所有鍵 print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有鍵值對 print(config.get('bitbucket.org','compression')) # yes get方法Section下的key對應的value
修改文件內容
import configparser config = configparser.ConfigParser() config.read('example.ini') #讀文件 config.add_section('yuan') #添加section config.remove_section('bitbucket.org') #刪除section config.remove_option('topsecret.server.com',"forwardx11") #刪除一個配置想 config.set('topsecret.server.com','k1','11111') config.set('yuan','k2','22222') with open('new2.ini','w') as f: config.write(f)
喜歡這篇文章?歡迎打賞~~