Python中的配置文件解析器(configparser)
Python标准库中的configparser模块定义了用于读取和写入MicrosoftWindowsOS使用的配置文件的功能。此类文件通常具有.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()
在此类中定义了以下方法-
get(),但将值转换为整数。get(),但是将值转换为浮点数。get(),但将值转换为布尔值。返回False或True。以下脚本读取并解析“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()