在Python中读取配置文件通常使用`configparser`模块,以下是使用`configparser`模块读取配置文件的步骤:
1. 创建配置文件(例如`config.ini`),内容如下:
[Section1]
key1 = value1
key2 = value2
[Section2]
key3 = value3
key4 = value4
2. 在Python代码中导入`configparser`模块,并创建一个`ConfigParser`对象:
import configparser
config = configparser.ConfigParser()
3. 使用`read()`方法读取配置文件:
config.read('config.ini')
4. 使用`get()`方法获取配置文件中的值:
value1 = config.get('Section1', 'key1')
value2 = config.get('Section1', 'key2')
value3 = config.get('Section2', 'key3')
value4 = config.get('Section2', 'key4')
5. 打印获取到的值:
print(value1) 输出: value1
print(value2) 输出: value2
print(value3) 输出: value3
print(value4) 输出: value4
以上步骤展示了如何使用`configparser`模块读取INI格式的配置文件。