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

二、基本的寫入操作:

  • -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) 

三、代碼示例

1、新建一個配置文件:config.ini,內容如下:

# 定義DATABASE分組
[DATABASE]
host = 50.23.190.57
username = xxxxxx
password = ******
port = 3306
database = databasename

2、在對配置文件進行讀寫操作前,我們需要先進行一個操作: 

# 實例化ConfigParser
config = configparser.ConfigParser()

3、進行配置文件的讀取操作。以get為例,示例代碼如下: 

# 讀取config.ini
config.read("config.ini")

# 讀取 [DATABASE] 分組下的 host 的值
value = config.get("DATABASE", "host")
print(value)

4、進行配置文件的寫入操作。以set(section, option, value)為例,示例代碼如下:

# 創建一個組:LILY
config.add_section("LILY")
# 給LILY組添加一個屬性name=lily
config.set("LILY", "name", "lily")
# 寫入 config.ini
# r:讀,r+:讀寫,w:寫,w+:寫讀,a:追加,a+:追加讀寫
# 寫讀和讀寫的區別:讀寫,文件已經存在;讀寫,創建新的文件
config.write(open('config.ini', 'a'))


免責聲明!

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



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