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

Python中configparser.ConfigParser模块实现INI配置文件的读取和写入

发布时间:2024-01-16 16:10:13

在Python中,configparser模块提供了一种简单方便的方式来读取和写入INI配置文件。INI文件是一种常用的配置文件格式,由一系列的节(section)和键值对(key-value)组成。

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

import configparser

接下来,我们可以创建一个ConfigParser对象,并使用read()方法来读取INI文件。假设我们有一个名为config.ini的文件,其内容如下:

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

[server]
ip = 127.0.0.1
port = 8000

使用代码读取该文件:

config = configparser.ConfigParser()
config.read('config.ini')

调用read()方法后,我们可以通过调用ConfigParser对象的相应方法来访问INI文件中的节和键值对。

首先,我们可以使用sections()方法获取所有的节(即配置的分类):

sections = config.sections()
print(sections)

输出结果为:

['database', 'server']

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

database_items = config.items('database')
print(database_items)

输出结果为:

[('host', 'localhost'), ('port', '3306'), ('username', 'root'), ('password', '123456')]

我们也可以直接使用options(section)方法获取指定节的所有键:

server_options = config.options('server')
print(server_options)

输出结果为:

['ip', 'port']

除了读取节和键值对之外,我们还可以根据节和键来获取具体的值。使用get(section, option)方法可以获取指定节的指定键的值:

database_host = config.get('database', 'host')
print(database_host)

输出结果为:

localhost

类似地,我们也可以使用getint(section, option)getfloat(section, option)getboolean(section, option)等方法来获取整数、浮点数和布尔值类型的值。

接下来,我们来看一下如何写入INI文件。

首先,我们可以使用add_section(section)方法来添加一个新的节:

config.add_section('logging')

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

config.set('logging', 'level', 'debug')

最后,我们可以使用write()方法将修改后的配置写入到文件中:

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

这样,我们就成功地将新的节和键值对写入了INI文件中。

综上所述,configparser模块提供了一种简单易用的方式来读取和写入INI配置文件。