欢迎访问宙启技术站
智能推送

Python中configparser.ConfigParser模块的用法

发布时间:2023-12-23 19:44:14

configparser模块是Python中用于读取、写入配置文件的标准模块,可以方便地读取和修改INI配置文件。下面是configparser模块的用法及示例。

首先,我们需要导入configparser模块:

import configparser

接下来,我们可以创建一个ConfigParser对象:

config = configparser.ConfigParser()

### 读取配置文件

configparser模块可以读取INI配置文件,其中包含了多个节(section)和键值对(key-value pair)。

假设我们有一个名为example.ini的配置文件,内容如下:

[database]
host = localhost
port = 3306
user = root
password = 123456

[server]
host = localhost
port = 8080

我们可以使用ConfigParser对象的read()方法将配置文件读取到内存中:

config.read('example.ini')

然后,我们可以使用sections()方法获取所有的节名:

print(config.sections())  # 输出: ['database', 'server']

使用options(section)方法可以获取指定节下的所有键名:

print(config.options('database'))  # 输出: ['host', 'port', 'user', 'password']

使用items(section)方法可以获取指定节下的所有键值对:

print(config.items('database'))  # 输出: [('host', 'localhost'), ('port', '3306'), ('user', 'root'), ('password', '123456')]

通过调用get(section, option)方法可以获取指定节中的指定键的值:

print(config.get('database', 'host'))  # 输出: localhost

### 写入配置文件

configparser模块还可以将配置写入INI配置文件。

我们可以使用ConfigParser对象的set(section, option, value)方法来设置指定节中的指定键的值:

config.set('server', 'host', '127.0.0.1')
config.set('server', 'port', '80')

然后,使用write(file_object)方法将配置写入文件:

with open('example.ini', 'w') as f:
    config.write(f)

这样,配置文件中的server节就被修改为:

[server]
host = 127.0.0.1
port = 80

### 创建新的配置文件

如果要创建一个新的INI配置文件,我们也可以使用configparser模块。

首先,创建一个ConfigParser对象:

config = configparser.ConfigParser()

然后,可以使用add_section(section)方法来创建新的节:

config.add_section('database')

接下来,可以使用set(section, option, value)方法来设置节中的键值对:

config.set('database', 'host', 'localhost')
config.set('database', 'port', '3306')
config.set('database', 'user', 'root')
config.set('database', 'password', '123456')

最后,使用write(file_object)将配置写入文件:

with open('example.ini', 'w') as f:
    config.write(f)

这样,就创建了一个名为example.ini的配置文件,并在其中添加了一个名为database的节。

以上就是configparser模块的用法及示例,它可以方便地读取和修改INI配置文件,是Python中常用的配置文件处理工具。