Python中configparser.ConfigParser模块的配置文件读取和写入示例教程
configparser模块是Python内置的用于读取和写入配置文件的工具。它支持基本的配置文件格式,如INI文件。
为了使用configparser模块,需要导入该模块:
import configparser
下面是一个configparser的配置文件读取和写入的示例教程,包含了使用例子:
## 1. 配置文件的格式
configparser支持基本的INI配置文件格式,该格式包含了section、option和value三个概念。一个配置文件可以包含多个section,每个section下可以有多个option和value。
下面是一个例子:
[database] host = localhost port = 3306 username = root password = password123 database = testdb [server] ip = 127.0.0.1 port = 8080
## 2. 配置文件的读取
使用configparser模块可以方便地读取配置文件中的内容。
首先,创建一个ConfigParser对象:
config = configparser.ConfigParser()
然后,使用ConfigParser对象的read()方法来读取配置文件:
config.read('config.ini')
读取后,可以通过ConfigParser对象的sections()方法获取配置文件中的所有section:
sections = config.sections() print(sections)
输出为:
['database', 'server']
使用ConfigParser对象的options()方法获取指定section下的所有option:
options = config.options('database')
print(options)
输出为:
['host', 'port', 'username', 'password', 'database']
使用ConfigParser对象的get()方法获取指定section和option下的value:
host = config.get('database', 'host')
print(host)
输出为:
localhost
## 3. 配置文件的写入
使用configparser模块也可以方便地写入配置文件。
首先,同样是创建一个ConfigParser对象:
config = configparser.ConfigParser()
然后,使用ConfigParser对象的add_section()方法添加section:
config.add_section('database')
使用ConfigParser对象的set()方法添加option和value:
config.set('database', 'host', 'localhost')
config.set('database', 'port', '3306')
config.set('database', 'username', 'root')
config.set('database', 'password', 'password123')
config.set('database', 'database', 'testdb')
最后,使用ConfigParser对象的write()方法将配置写入文件:
with open('config.ini', 'w') as configfile:
config.write(configfile)
## 4. 示例代码
下面是完整的示例代码:
import configparser
# 读取配置文件
config = configparser.ConfigParser()
config.read('config.ini')
# 获取所有section
sections = config.sections()
print(sections)
# 获取指定section下的所有option
options = config.options('database')
print(options)
# 获取指定section和option下的value
host = config.get('database', 'host')
print(host)
# 写入配置文件
config = configparser.ConfigParser()
config.add_section('database')
config.set('database', 'host', 'localhost')
config.set('database', 'port', '3306')
config.set('database', 'username', 'root')
config.set('database', 'password', 'password123')
config.set('database', 'database', 'testdb')
with open('config.ini', 'w') as configfile:
config.write(configfile)
以上就是使用configparser模块进行配置文件的读取和写入的示例教程。通过这个示例教程,可以方便地读取和写入配置文件。
