Python 之ConfigParser模組
阿新 • • 發佈:2020-10-12
前言
在做專案的時候一些配置檔案都會寫在settings配置檔案中,今天在研究"州的先生"開源文件寫作系統-MrDoc的時候,發現部分配置檔案寫在config.ini中,並利用configparser進行相關配置檔案的讀取及修改。
一、ConfigParser模組簡介
該模組適用於配置檔案的格式與windows ini檔案類似,是用來讀取配置檔案的包。配置檔案的格式如下:中括號“[ ]”內包含的為section。section 下面為類似於key-value 的配置內容。格式如下:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = Atlan [topsecret.server.com] Port = 50022 ForwardX11 = no
括號“[ ]”內包含的為section。緊接著section 為類似於key-value 的options 的配置內容。
二、ConfigParser模組使用
1.寫入操作
程式碼如下:
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) #將物件寫入檔案 以上程式碼做個簡單的解釋,和字典的操作方式相比,configparser模組的操作方式,無非是在例項化的物件後面,跟一個section,在緊跟著設定section的屬性(類似字典的形式) config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' } #類似於操作字典的形式 #config後面跟的是一個section的名字,section的段的內容的建立類似於建立字典。類似與字典當然還有別的操作方式啦! config['bitbucket.org'] = {'User':'Atlan'} #類似於最經典的字典操作方式
2.讀取操作
import configparser config = configparser.ConfigParser() #---------------------------查詢檔案內容,基於字典的形式 print(config.sections()) # [] config.read('example.ini',encoding='utf-8') print(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] print('bytebong.com' in config) # False print('bitbucket.org' in config) # True print('DEFAULT' 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) #user serveraliveinterval compression compressionlevel forwardx11 # 同for迴圈,找到'bitbucket.org'下所有鍵 ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11'] print(config.options('bitbucket.org')) print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有鍵值對 [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'Atlan')] print(config.get('bitbucket.org','compression')) # yes get方法Section下的key對應的value print(config.getboolean('bitbucket.org','compression')) # True
3.修改操作
import configparser config = configparser.ConfigParser() config.read('example.ini',encoding='utf-8') #讀檔案 config.add_section('yuan') #新增section config.remove_section('bitbucket.org') #刪除section config.remove_option('topsecret.server.com',"forwardx11") #刪除一個配置項 # 修改某個option的值,如果不存在該option 則會建立 config.set('topsecret.server.com','k1','11111') config.set('yuan','k2','22222') #寫回檔案 config.write(open("example.ini", "w")) # 寫到其他檔案 with open('new2.ini','w') as f: config.write(f)