本篇文章主要介绍Python的配置文件INI 格式的操作
ini文件是一种常见的配置文件格式,Python提供了标准库configparser
来轻松读写ini文件。下面我们来详细了解一下如何使用Python操作ini文件~
基本结构速览
一个典型的ini文件长这样:
1
2
3
4
5
6
7
|
[Section1]
key1 = value1
key2 = value2
[Section2]
keyA = valueA
keyB = valueB
|
基础操作四连
🔸 读取ini文件
1
2
3
4
5
6
7
8
9
10
11
12
13
|
import configparser
config = configparser.ConfigParser()
config.read('config.ini') # (๑•̀ㅂ•́)و✧ 读取成功!
# 获取所有section
sections = config.sections() # ['Section1', 'Section2']
# 获取某个section下的所有option
options = config.options('Section1') # ['key1', 'key2']
# 获取具体值
value = config.get('Section1', 'key1') # 'value1'
|
🔸 写入ini文件
1
2
3
4
5
6
7
8
9
10
11
|
config = configparser.ConfigParser()
# 添加section和值
config['DEFAULT'] = {'ServerAliveInterval': '45'}
config['SectionA'] = {}
config['SectionA']['User'] = 'Alice'
config['SectionA']['Age'] = '25' # 注意:所有值都会被转换为字符串
# 写入文件
with open('new_config.ini', 'w') as f:
config.write(f) # ୧(﹒︠ᴗ﹒︡)୨ 保存成功!
|
🔸 修改配置
1
2
3
|
config.set('SectionA', 'Age', '26') # 修改Age的值
config.add_section('NewSection') # 添加新section
config.remove_option('SectionA', 'User') # 删除选项
|
🔸 类型转换
1
2
3
4
|
# 自动转换为相应类型
is_alive = config.getboolean('DEFAULT', 'ServerAliveInterval')
port = config.getint('SectionA', 'Port')
ratio = config.getfloat('SectionA', 'Ratio')
|
高级技巧五连击
💡 默认值处理
1
2
|
# 当键不存在时返回默认值
value = config.get('Section1', 'nonexist_key', fallback='default_value')
|
💡 检查存在性
1
2
3
4
5
|
if 'Section1' in config:
print("Section1存在!(ノ◕ヮ◕)ノ*:・゚✧")
if config.has_option('Section1', 'key1'):
print("key1存在!")
|
💡 字典式访问
1
2
3
4
5
|
# 像字典一样操作
for section in config:
print(f"[{section}]")
for key in config[section]:
print(f"{key} = {config[section][key]}")
|
💡 插值处理
1
2
3
4
5
6
7
|
config['Paths'] = {
'home_dir': '/Users',
'my_dir': '%(home_dir)s/Alice', # 会解析为 /Users/Alice
'my_pictures': '%(my_dir)s/Pictures'
}
print(config['Paths']['my_pictures']) # 输出: /Users/Alice/Pictures
|
💡 保留注释和空格(需要使用RawConfigParser)
1
2
3
4
|
from configparser import RawConfigParser
config = RawConfigParser()
config.read('config_with_comments.ini') # 保留原始注释内容
|
注意事项小贴士
- ✨ 所有值都以字符串形式存储,读取时需要类型转换
- ✨
DEFAULT
是一个特殊section,其他section会继承它的键值
- ✨ Windows路径建议使用raw字符串或双反斜杠:
r'C:\path'
或 'C:\\path'
- ✨ 大型配置文件考虑使用JSON或YAML格式
- ✨ Python 3.2+推荐使用
configparser
,Python 2中使用ConfigParser
完整示例
下面是一个完整的操作示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import configparser
# 创建配置
config = configparser.ConfigParser()
config['DEFAULT'] = {
'debug': 'True',
'log_level': 'INFO'
}
config['database'] = {
'host': 'localhost',
'port': '5432',
'name': 'mydb'
}
# 保存配置
with open('app_config.ini', 'w') as f:
config.write(f)
# 读取配置
new_config = configparser.ConfigParser()
new_config.read('app_config.ini')
# 使用配置
debug_mode = new_config.getboolean('DEFAULT', 'debug')
db_host = new_config['database']['host']
print(f"Debug模式: {debug_mode}, 数据库主机: {db_host}")
|
🌟 总结
Python的configparser
模块使ini文件操作变得简单高效。无论是小型应用配置还是系统设置,都能轻松应对。快去试试吧!(๑˃̵ᴗ˂̵)و
小提示:需要更复杂的配置管理?可以看看PyYAML
或toml
模块哦~