Pythonconfigparser.ConfigParser模块的用法及实例讲解
发布时间:2023-12-24 07:33:27
Python中的configparser模块是用于读取和写入配置文件的工具,常用于存储程序的配置参数。
ConfigParser模块提供了一个ConfigParser类,可以通过这个类来进行配置文件的读取和写入操作。下面是一些常用的方法:
1.创建ConfigParser对象:
import configparser config = configparser.ConfigParser()
2.读取配置文件:
config.read('config.ini')
read()方法用于读取配置文件,参数是配置文件的路径。如果读取成功,会返回一个包含配置文件路径的列表。
3.获取配置项的值:
value = config.get(section, option)
get()方法用于获取指定section中指定option的值。
4.获取全部配置项:
options = config.options(section)
options()方法用于获取指定section中的所有配置项,返回一个包含所有配置项的列表。
5.获取指定section中的所有键值对:
items = config.items(section)
items()方法用于获取指定section中的所有键值对,返回一个包含所有键值对的列表。
6.写入配置文件:
config.set(section, option, value)
config.write(open('config.ini', 'w'))
set()方法用于向指定section中写入或修改配置项的值。write()方法用于将配置信息写入配置文件。
下面是一个实例,假设配置文件config.ini内容如下:
[Server] host = localhost port = 8080 [Database] username = root password = 123456
可以使用configparser模块来读取和修改这个配置文件:
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# 获取Server中的host和port配置项的值
host = config.get('Server', 'host')
port = config.getint('Server', 'port')
print(f'Server: {host}:{port}')
# 获取Database中的username和password配置项的值
username = config.get('Database', 'username')
password = config.get('Database', 'password')
print(f'Database: {username}:{password}')
# 修改host和port配置项的值
config.set('Server', 'host', 'example.com')
config.set('Server', 'port', '8888')
# 将修改后的配置写入配置文件
config.write(open('config.ini', 'w'))
运行结果:
Server: localhost:8080 Database: root:123456
配置文件config.ini内容被读取并解析到config对象中,通过调用get()方法可以获取配置项的值,并输出到控制台。然后通过调用set()方法可以修改配置项的值,最后通过write()方法将修改后的配置写入配置文件。
以上就是configparser模块的使用方法及实例,使用configparser可以方便地读取和写入配置文件,适用于配置程序参数、保存用户设置等功能。
