python基础--ConfigParser模块读写配置文件

configParser 模块用于操作配置文件

该模块支持读取类似如上格式的配置文件,如 windows 下的 .conf 及 .ini 文件等。可以包含一个或多个节(section),每个节可以有多个参数(键=值)。

配置文件的格式是: []包含的叫section,    section 下有option=value这样的键值

[db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = test

[openapi]
openapi_host= https://www.c.com
api_key = abc
secretKey = 123

 

基础读取配置文件

  • -read(filename)               直接读取文件内容
  • -sections()                      得到所有的section,并以列表的形式返回
  • -options(section)            得到该section的所有option
  • -items(section)                得到该section的所有键值对
  • -get(section,option)        得到section中option的值,返回为string类型
  • -getint(section,option)    得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

 

# -* - coding: UTF-8 -* -  
import ConfigParser

cur_path = os.path.dirname(os.path.realpath(__file__))
configPath = os.path.join(cur_path, "test.conf")
conf = configparser.ConfigParser() # 相当于一个空字典
conf.read(configPath, encoding='utf-8')
# 获取指定的section, 指定的option的值 
db_port = conf.get("db", "db_port")
print(db_port)
db_user
= conf.get("db", "db_user")
print db_user

#获取所有的section
sections = conf.sections()
print sections

#写配置文件

# 更新指定section, option的值
conf.set("db", "port", "3417")

# 写入指定section, 增加新option的值
conf.set("openapi", "Port", "80")

# 添加新的
section
conf.add_section("new_section")
conf.set(
"new_section", "new_option", "test")

# 写回配置文件
conf.write(open("test.conf","w"))

 

posted @ 2020-08-24 15:06  milkty  阅读(126)  评论(0)    收藏  举报