python configobj 配置文件神器

pip install configobj
[general]
name = Python之神
version = 3.10
debug = True

[database]
host = localhost
port = 3306
user = root
password = 123456
from configobj import ConfigObj

# 创建一个ConfigObj对象,它会自动读取并解析config.ini文件
config = ConfigObj('config.ini')
# 创建ConfigObj对象时,指定编码格式为 'utf-8'
# config = ConfigObj('config.ini', encoding='utf-8')

# 读取配置项,就像操作Python字典一样简单!
print(config['general']['name'])   # 输出: Python之神
print(config['database']['host'])  # 输出: localhost
print(config['general']['debug'])  # 输出: True

嵌套模式

[server]
  [main]
  host = 127.0.0.1
  port = 8080
  protocol = http

  [backup]
  host = 127.0.0.2
  port = 8081
  protocol = https

  [dev_env]
  host = 0.0.0.0
  port = 5000
  debug = True
from configobj import ConfigObj

server_config = ConfigObj('server.ini')

# 读取主服务器的 host
print(server_config['server']['main']['host'])    # 输出: 127.0.0.1

# 读取备用服务器的 port
print(server_config['server']['backup']['port'])  # 输出: 8081

# 读取开发环境的 debug 模式
print(server_config['server']['dev_env']['debug']) # 输出: True

# 甚至可以像字典一样遍历子节
print("\n遍历所有服务器配置:")
for server_type, settings in server_config['server'].items():
    print(f"  [{server_type}]")
    for key, value in settings.items():
        print(f"    {key} = {value}")

作者:spike

分类: Python

创作时间:2025-10-18

更新时间:2025-10-19

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1