python怎么读取配置文件

在Python中,可以使用configparser模块来读取配置文件。以下是一个简单的示例:

首先,创建一个名为config.ini的配置文件,内容如下:

[Section1]
key1 = value1
key2 = value2

[Section2]
key3 = value3
key4 = value4

在Python代码中,导入configparser模块,并创建一个ConfigParser对象:

import configparser

config = configparser.ConfigParser()

使用read()方法读取配置文件:

config.read('config.ini')

现在可以通过get()方法来获取配置文件中的值:

value1 = config.get('Section1', 'key1')
value2 = config.get('Section1', 'key2')
value3 = config.get('Section2', 'key3')
value4 = config.get('Section2', 'key4')

print(value1)  # 输出:value1
print(value2)  # 输出:value2
print(value3)  # 输出:value3
print(value4)  # 输出:value4

以上就是使用configparser模块读取配置文件的基本步骤。可以根据实际需求来进行配置文件的读取和处理。

阅读剩余
THE END