python讀取配置文件


配置文件作為一種可讀性很好的格式,非常適用於存儲程序中的配置數據。 在每個配置文件中,配置數據會被分組(比如“config”和 “cmd”)。 每個分組在其中指定對應的各個變量值。如下:

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

基本的讀取操作:

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

在對配置文件進行讀寫操作前,我們需要先進行以下兩個操作:

1、實例化ConfigParser對象:

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

2、讀取配置文件

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

然后進行配置文件的讀取操作。

以get為例,示例代碼如下:

# 定義方法,獲取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)方法,可以獲取指定分組下指定名稱的值,其他方法類似,可參照着嘗試。

基本的寫入操作:

  • -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)為例,示例代碼如下:

# 定義方法,修改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的學習道路,希望大家於我同行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM