python ConfigParser读取和写入参数
时间: 2024-05-15 15:16:46 浏览: 91
ConfigParser是Python的一个标准库,用于读取和写入配置文件。配置文件一般是一些键值对的集合,可以用来存储程序的参数、选项等信息,以便程序启动时加载和使用。
下面是一个简单的示例,演示如何使用ConfigParser读取和写入参数:
读取参数:
```python
import configparser
# 创建ConfigParser对象
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 读取参数
name = config.get('section1', 'name')
age = config.getint('section1', 'age')
height = config.getfloat('section1', 'height')
is_student = config.getboolean('section1', 'is_student')
# 输出参数
print('name:', name)
print('age:', age)
print('height:', height)
print('is_student:', is_student)
```
写入参数:
```python
import configparser
# 创建ConfigParser对象
config = configparser.ConfigParser()
# 添加参数
config.add_section('section1')
config.set('section1', 'name', 'Alice')
config.set('section1', 'age', '20')
config.set('section1', 'height', '1.70')
config.set('section1', 'is_student', 'True')
# 写入配置文件
with open('config.ini', 'w') as configfile:
config.write(configfile)
```
在写入参数时,需要先创建ConfigParser对象,然后使用add_section()和set()方法添加参数,最后调用write()方法将参数写入配置文件。配置文件默认使用INI格式,可以通过参数指定其他格式。
阅读全文
相关推荐

















