python配置文件
时间: 2023-10-21 19:26:43 浏览: 34
对于Python的配置文件,通常使用的是INI文件格式。INI文件是一种简单的文本文件,用于存储配置信息。INI文件由一系列的节(section)和键值对(key-value pair)组成。
下面是一个示例的INI配置文件:
```ini
; 这是注释行,以分号开头
[database]
host = localhost
port = 3306
username = admin
password = 123456
[server]
ip = 192.168.0.1
port = 8080
timeout = 60
```
在Python中,可以使用标准库中的`configparser`模块来读取和解析INI配置文件。下面是一个简单的示例代码:
```python
import configparser
# 创建一个ConfigParser对象
config = configparser.ConfigParser()
# 读取配置文件
config.read('config.ini')
# 获取某个节中的键值对
db_host = config.get('database', 'host')
db_port = config.getint('database', 'port')
db_username = config.get('database', 'username')
db_password = config.get('database', 'password')
# 输出配置信息
print(f"Database host: {db_host}")
print(f"Database port: {db_port}")
print(f"Database username: {db_username}")
print(f"Database password: {db_password}")
```
通过上述代码,你可以读取INI文件中的配置项,并将其用于你的Python程序中。你可以根据需要修改或扩展这个示例代码来满足你的具体需求。