python 操作 .ini 文件
时间: 2024-10-13 20:16:15 浏览: 44
在Python中操作.ini文件通常可以使用标准库`configparser`模块。这个模块提供了一种简单的方式来读取、写入和配置INI格式的配置文件,比如`.ini`文件。以下是基本步骤:
1. 导入库:
```python
import configparser
```
2. 读取文件:
```python
config = configparser.ConfigParser()
config.read('path_to_your_file.ini')
sections = config.sections() # 获取所有节名
options_per_section = config.items('section_name') # 获取特定节的所有键值对
value = config.get('section_name', 'option_name') # 获取指定项的值
```
3. 写入文件:
```python
config['section_name'] = {'option_name': 'new_value'}
with open('path_to_your_file.ini', 'w') as configfile:
config.write(configfile)
```
4. 示例:
```python
# 读取
config.read('settings.ini')
print(config['database']['host'])
# 写入
config['database']['password'] = 'your_secret'
with open('settings.ini', 'w') as configfile:
config.write(configfile)
```
阅读全文
相关推荐
















