python讀取配置文件

配置文件做爲一種可讀性很好的格式,很是適用於存儲程序中的配置數據。 在每一個配置文件中,配置數據會被分組(好比「config」和 「cmd」)。 每一個分組在其中指定對應的各個變量值。以下:css

# 定義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

基本的讀取操做:python

  • -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() 函數。

在對配置文件進行讀寫操做前,咱們須要先進行如下兩個操做:swift

一、實例化ConfigParser對象:app

# 實例化configParser對象 cf = configparser.ConfigParser()

二、讀取配置文件函數

# 讀取config.ini文件 cf.read(config.ini)

而後進行配置文件的讀取操做。學習

以get爲例,示例代碼以下:spa

# 定義方法,獲取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

經過get(section, option)方法,能夠獲取指定分組下指定名稱的值,其餘方法相似,可參照着嘗試。code

基本的寫入操做:orm

  • -write(fp)  將config對象寫入至某個 .init 格式的文件  Write an .ini-format representation of the configuration state.
  • -add_section(section)   添加一個新的section
  • -set( section, option, value   對section中的option進行設置,須要調用write將內容寫入配置文件
  • -remove_section(section)  刪除某個 section
  • -remove_option(section, option) 

以set(section, option, value)爲例,示例代碼以下:server

# 定義方法,修改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") 

在解析時,getboolean()方法查找任何可行的值,例如如下幾個都是等價的:

# 如下取得的值都是等價的爲ture [log] log_error=true log_error=TRUE log_error=1 log_error=yes

以上就是我初次學習的一點記錄,若有錯誤的地方,但願你們慷慨指出,我會及時改正,若是本篇對你有些幫助,但願給我點個贊哦!接下來我會繼續python的學習道路,但願你們於我同行。

相關文章
相關標籤/搜索