您的位置:

Python配置文件解析器PythonConfigParser详解

在开发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格式的配置文件,提供了别名功能,不区分大小写,实现方便。