在開發Python應用程序時,有很多情況需要用到配置文件。Python提供了一個標準庫叫做ConfigParser,可以用來解析常見的配置文件,如INI格式配置文件、Conf格式配置文件。PythonConfigParser模塊解析的配置文件,通常會具有類似於key-value的結構。
一、PythonConfigParser 簡介
Python ConfigParser 模塊提供了一個在Python中讀寫INI格式文件的類。使用此模塊,可以輕鬆地讀取、編輯和創建INI格式文件,即鍵值對形式的配置文件。PythonConfigParser模塊從Python2.3引入,到目前為止,Python2,Python3均支持此模塊。
PythonConfigParser模塊提供的功能非常簡單而有用,它可以幫助我們快速地讀取INI格式的配置文件,實現對配置文件的讀取、修改和操作。 在使用PythonConfigParser模塊時,需要注意文件的字符集編碼,讀取操作使用方法ConfigParser.read(file, encoding=None)。
import configparser
config = configparser.ConfigParser()
print(config.read('example.cfg'))
print(config.sections())
輸出:
['example.cfg']
['debug', 'server', 'client', 'database']
在這個示例中,我們首先導入了Python提供的configparser模塊。然後,使用ConfigParser()方法創建了一個配置文件解析器對象config。
接着,我們調用了config.read()方法,讀取我們的示例配置文件example.cfg。然後,用config.sections()方法獲得了example.cfg文件中包含的所有部分的列表。
二、PythonConfigParser 的常用方法
1、section()方法
ConfigParser類中的section()方法用於返回所有的section。section()方法沒有參數。返回一個包含所有section的列表。
import configparser
config = configparser.ConfigParser()
config.read('test.ini')
for section_name in config.sections():
print('Section:', section_name)
輸出:
Section: Debug
Section: Database
Section: Local
Section: Remote
2、options()方法
options(section)方法返回給定section中的所有options。返回值類型為列表(list)。
import configparser
config = configparser.ConfigParser()
config.read('test.ini')
for section_name in config.sections():
print('Section:', section_name)
print(' Options:', config.options(section_name))
輸出:
Section: Debug
Options: ['name', 'host', 'port', 'command']
Section: Database
Options: ['name', 'host', 'port']
Section: Local
Options: ['enabled']
Section: Remote
Options: ['enabled', 'port']
3、get()方法
get(section, option)方法用於獲取指定section中option的值。返回一個字符串。要獲取的section和option名稱是大小寫不敏感的。
import configparser
config = configparser.ConfigParser()
config.read('test.ini')
for section_name in config.sections():
print('Section:', section_name)
print(' Options:', list(config.options(section_name)))
for name, value in config.items(section_name):
print(' %s = %s' % (name, value))
print(config.get('Debug', 'name'))
輸出:
Section: Debug
Options: ['name', 'host', 'port', 'command']
name = config.ini
host = localhost
port = 9000
command = /usr/local/bin/something
Section: Database
Options: ['name', 'host', 'port']
name = config
host = 127.0.0.1
port = 5432
Section: Local
Options: ['enabled']
enabled = true
Section: Remote
Options: ['enabled', 'port']
enabled = false
port = 2121
config.ini
4、items()方法
items(section)方法返回所有配置條目(key-value)的元組列表。即返回值類型為列表(list),元素為元組(tuple)。
import configparser
config = configparser.ConfigParser()
config.read('test.ini')
for section_name in config.sections():
print('Section:', section_name)
print(' Options:', list(config.options(section_name)))
for name, value in config.items(section_name):
print(' %s = %s' % (name, value))
輸出:
Section: Debug
Options: ['name', 'host', 'port', 'command']
name = config.ini
host = localhost
port = 9000
command = /usr/local/bin/something
Section: Database
Options: ['name', 'host', 'port']
name = config
host = 127.0.0.1
port = 5432
Section: Local
Options: ['enabled']
enabled = true
Section: Remote
Options: ['enabled', 'port']
enabled = false
port = 2121
三、PythonConfigParser 的常見應用
1、讀取配置文件
我們可以使用PythonConfigParser解析常見的配置文件,例如ini文件、conf文件,首先需要通過ConfigParser()方法創建一個配置文件解析器對象,然後使用read()方法讀取配置文件。
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
print(config.sections())
輸出:
['DEFAULT', 'path']
2、使用PythonConfigParser 更新配置文件
當我們需要更新配置文件時,兩種方法可行:第一,我們可以使用ConfigParser生成配置文件;第二,我們可以使用ConfigParser操作現有的配置文件,然後將修改後的內容寫入原有的配置文件。
如果需要添加一個新的配置,則可以通過set()方法實現。如果需要更新現有配置,則可以通過set()方法修改現有配置;如果需要在不覆蓋原有配置情況下,添加新的信息,可以通過add_section()方法添加新的配置信息。
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
print(config.get('path', 'database'))
config.set('path', 'database', 'test.db')
config.add_section('test')
config.set('test', 'hello', 'world')
with open('example.ini', 'w') as f:
config.write(f)
輸出:
sqlite:///:memory:
3、使用PythonConfigParser 生成配置文件
如果要新建一個配置文件,可以使用PythonConfigParser。首先需要創建一個對象,然後使用add_section()方法添加分區信息,使用set()方法添加選項和值,最後通過write()方法將配置文件寫入目標文件。
import configparser
config = configparser.ConfigParser()
config.add_section('test')
config.set('test', 'hello', 'world')
with open('example.ini', 'w') as f:
config.write(f)
輸出:
; Automatically generated configuration file for example
[DEFAULT]
[path]
database = sqlite:///:memory:
[test]
hello = world
四、總結
PythonConfigParser 模塊非常方便,可以快速、準確地讀取和寫入常見的配置文件。PythonConfigParser可以解析INI格式的配置文件,提供了別名功能,不區分大小寫,實現方便。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/181364.html