Python 配置檔案解析器 (configparser)


Python 標準庫中的 `configparser` 模組定義了讀取和寫入 Microsoft Windows 作業系統使用的配置檔案的功能。此類檔案通常具有 .INI 副檔名。

INI 檔案由節組成,每個節都以 `[section]` 標題開頭。在方括號中,我們可以放置節的名稱。節之後是鍵/值條目,由 = 或 : 字元分隔。它可能包含註釋,以 # 或 ; 符號為字首。下面顯示了一個示例 INI 檔案:

[Settings]
# Set detailed log for additional debugging info
DetailedLog=1
RunStatus=1
StatusPort=6090
StatusRefresh=10
Archive=1
# Sets the location of the MV_FTP log file
LogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
Version=0.9 Build 4
ServerName=Unknown

[FTP]
# set the FTP server active
RunFTP=1
# defines the FTP control port
FTPPort=21
# Sets the location of the FTP data directory
FTPDir=/opt/ecs/mvuser/MV_IPTel/data/FTPdata
# set the admin Name
UserName=admin
# set the Password
Password=admin

`configparser` 模組具有 `ConfigParser` 類。它負責解析配置檔案列表並管理已解析的資料庫。

使用以下語句建立 `ConfigParser` 物件:

parser = configparser.ConfigParser()

在這個類中定義了以下方法:

sections()返回所有配置檔案節的名稱。
has_section()返回給定節是否存在。
has_option()返回給定選項在給定節中是否存在。
options()返回命名節的配置選項列表。
read()讀取並解析指定的配置檔案。
read_file()讀取並解析一個配置檔案,以檔案物件的形式給出。
read_string()從給定字串中讀取配置。
read_dict()從字典中讀取配置。鍵是節名,值是包含鍵和值(這些鍵值應該存在於該節中)的字典。
get()返回命名選項的字串值。
getint()類似於 get(),但將值轉換為整數。
getfloat()類似於 get(),但將值轉換為浮點數。
getboolean()類似於 get(),但將值轉換為布林值。返回 False 或 True。
items()返回一個元組列表,其中每個元組包含節中每個選項的 (名稱,值)。
remove_section()刪除給定的節及其所有選項。
remove_option()從給定節中刪除給定選項。
set()設定給定的選項。
write()以 .ini 格式寫入配置狀態。

以下指令碼讀取並解析 'sampleconfig.ini' 檔案

import configparser
parser = configparser.ConfigParser()
parser.read('sampleconfig.ini')
for sect in parser.sections():
   print('Section:', sect)
   for k,v in parser.items(sect):
      print(' {} = {}'.format(k,v))
   print()

輸出

Section: Settings
detailedlog = 1
runstatus = 1
statusport = 6090
statusrefresh = 10
archive = 1
logfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
version = 0.9 Build 4
servername = Unknown

Section: FTP
runftp = 1
ftpport = 21
ftpdir = /opt/ecs/mvuser/MV_IPTel/data/FTPdata
username = admin
password = admin

`write()` 方法用於建立配置檔案。以下指令碼配置解析器物件並將其寫入表示 'test.ini' 的檔案物件。

import configparser
parser = configparser.ConfigParser()
parser.add_section('Manager')
parser.set('Manager', 'Name', 'Ashok Kulkarni')
parser.set('Manager', 'email', 'ashok@gmail.com')
parser.set('Manager', 'password', 'secret')
fp=open('test.ini','w')
parser.write(fp)
fp.close()

更新於:2019年7月30日

13K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告