读取ini配置文件

[TOC]

读取配置文件

configparser

简单使用

配置文件示例

[db]
db_host = localhost  ds
db_port = 3306
db_user = root
db_passwd = "root"

[server]
server_ip = localhost

读取程序

# coding: utf-8
from configparser import ConfigParser

cf = ConfigParser()
cf.read("config.ini")

print(cf.get("db", "db_host"))
print(cf.get("db", "db_port"))
print(cf.get("db", "db_user"))
print(cf.get("db", "db_passwd"))

print(cf.get("server", "server_ip"))

输出

更多

写一个配置文件

代码

写入结果

File: example.ini

读取生成的配置文件

代码

读取结果

回退值

ini配置文件格式

  • A configuration file consists of sections, each led by a [section] header, followed by key/value entries separated by a specific string (= or : by default [1]).

  • By default, section names are case sensitive but keys are not.

  • Leading and trailing whitespace is removed from keys and values.

示例

最后更新于

这有帮助吗?