python學習筆記之讀取配置檔案
阿新 • • 發佈:2021-07-12
1.配置一個.int檔案用來寫配置檔案,例如
# 定義config分組 [config] platformName=Android appPackage=com.romwe appActivity=com.romwe.SplashActivity # 定義cmd分組 [cmd] viewPhone=adb devices startServer=adb start-server stopServer=adb kill-server # 定義log分組 [log] log_error=true
2.基本的讀操作
- -read(filename) 直接讀取檔案內容
- -sections() 得到所有的section,並以列表的形式返回
- -options(section) 得到該section的所有option
- -items(section) 得到該section的所有鍵值對
- -get(section,option) 得到section中option的值,返回為string型別
- -getint(section,option) 得到section中option的值,返回為int型別,還有相應的getboolean()和getfloat() 函式。
在對配置檔案進行讀寫操作前,我們需要先進行以下兩個操作:
- 例項化ConfigParser物件:
# 例項化configParser物件 cf = configparser.ConfigParser()
2.讀取配置檔案
# 讀取config.ini檔案 cf.read(config.ini)
然後進行配置檔案的讀取操作
# 定義方法,獲取config分組下指定name的值 def getConfigValue(self, name): value = self.cf.get("config", name) return value # 定義方法,獲取cmd分組下指定name的值 def getCmdValue(self, name): value = self.cf.get("cmd", name) return value
基本的寫入操作:
- -write(fp)將config物件寫入至某個 .init 格式的檔案Writean.ini-formatrepresentationoftheconfigurationstate.
- -add_section(section)新增一個新的section
- -set( section, option, value 對section中的option進行設定,需要呼叫write將內容寫入配置檔案
- -remove_section(section)刪除某個 section
- -remove_option(section, option)
# 定義方法,修改config分組下指定name的值value def setConfigValue(self, name, value): cfg = self.cf.set("config", name, value) fp = open(r'config.ini', 'w') cfg.write(fp)
配置檔案中的名字是不區分大小寫的,如下兩個是等價的
# 不區分大小寫,以下兩個等價,都獲取appActivity的值 self.cf.get("config", "appActivity") self.cf.get("config", "APPACTIVITY")