1. 程式人生 > 實用技巧 >ConfigParser模組詳解

ConfigParser模組詳解

ConfigParser模組介紹

在程式中使用配置檔案來靈活的配置一些引數是一件很常見的事情,配置檔案的解析並不複雜,在python裡更是如此,在官方釋出的庫中就包含有做這件事情的庫,那就是ConfigParser,這裡簡單的做一些介紹。
ConfigParser解析的配置檔案的格式為.ini的配置檔案格式,就是檔案中由多個section構成,每個section下又有多個配置項。

配置檔案格式如下:

  • 中括號“[ ]”內包含的為section。
  • section 下面為類似於key-value 的配置內容。

[HOST]  
HOST1 = 172.25.254.1:root:123
HOST2 = 172.25.254.2:root:123
HOST3 = 172.25.254.3:root:123

[db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = westos

ConfigParser模組初始化

import configparser  # 匯入模組

config = configparser.ConfigParser()  # 例項化ConfigParser物件
config.read('test.ini')  # 讀取配置檔案

ConfigParser模組常用方法

檢視節點

# 獲取sections
print(config.sections())

# 獲取某一sections下的所有的options
print(config.options('db'))

# 獲取某一sections下的items
print(config.items('db'))

# 獲取某一具體的value值
res = config.get('db', 'db_host')
print(res, type(res))

檢查節點

# 檢查檔案中是否存在某個節點。如果存在,返回True;否則,返回False;
config.has_section("db")  # True

config.has_section("port")  # False


# 檢查檔案中的某個節點是否存在某個key(eg:db_pass);如果存在,返回True;否則,返回False;
config.has_option("db","db_pass")  # True

config.has_option("db","db_passwd")  # False

新增節點

# 新增指定的節點
config.add_section("info")

# 往節點裡面新增對應的key-value值;
config.set("info","username","root")
config.set("info","password","westos")

# 將新增的內容真正寫入檔案中;
config.write(open("config.ini","w"))

刪除節點

# 刪除指定節點中的key值;如果成功刪除,返回True,否則,返回False;
config.remove_option("info","password")  # True
config.remove_option("info","username")  # True

# 刪除指定的節點;
conf.remove_section("info")  # True

# 將刪除的內容在檔案中真正刪除;
config.write(open("config.ini","w"))