Python 标准库的 ConfigParser 模块提供了一套完整的 API 来读取和操作配置文件。

文件格式

配置文件中包含一个或多个 section,每个 section 都有自己的 option;section 用 [sect_name] 表示,每个 option 是一个键值对,使用分隔符 = 或者 : 隔开;在 option 分隔符两端的空格会被忽略掉;配置文件使用 # 注释;

示例配置文件 dbconf.cfg;

[dbconfig]# 数据库读库链接信息host=127.0.0.1user=rootpasswd=rootdatabase=banma_financeport=3306

示例配置文件 book.info

[book]# 标题title: Core Pythonversion: 2016009021[hardcopy]pages:350

操作配置文件

配置文件的读取

1 实例化 ConfigParser

# 实例化 CoinfigParser 并加载配置文件# 实例化 dbconf 的解析器db_config_parser = ConfigParser.SafeConfigParser()db_config_parser.read('dbconf.cfg')# 实例化 book_info 的解析器book_info_parser = ConfigParser.SafeConfigParser()book_info_parser.read('book.info')

2 读取文件节点信息

# 获取 section 信息print db_config_parser.sections()print book_info_parser.sections()# 打印书籍的大写名称print string.upper(book_info_parser.get("book","title"))print "by", book_info_parser.get("book","author")# 格式化输出 dbconf 中的配置信息for section in db_config_parser.sections(): print section for option in db_config_parser.options(section): print " ", option,"=",db_config_parser.get(section,option)

输出结果:

['dbconfig']['book', 'hardcopy']CORE PYTHONby Jackdbconfig host = 127.0.0.1 user = root passwd = root database = banma_finance port = 3306

配置文件的写入

配置文件的写入与配置文件的读取方式基本一致,都是先操作对应的section,然后在 section 下面写入对应的 option;

# !/usr/bin/python# coding:utf-8import ConfigParserimport sys# 初始化 ConfigParserconfig_writer = ConfigParser.ConfigParser()# 添加 book 节点config_writer.add_section("book")# book 节点添加 title,author 配置config_writer.set("book","title","Python: The Hard Way")config_writer.set("book","author","anon")# 添加 ematter 节点和 pages 配置config_writer.add_section("ematter")config_writer.set("ematter","pages",250)# 将配置信息输出到标准输出config_writer.write(sys.stdout)# 将配置文件输出到文件config_writer.write(open('new_book.info','w'))

输出结果:

[book]title = Python: The Hard Wayauthor = anon [ematter]pages = 250

配置文件的更新

配置文件的更新操作,可以说是读取和写入的复合操作。如果没有最终的 write 操作,对于配置文件的读写都不会真正改变配置文件信息。

# !/usr/bin/python# coding:utf-8import ConfigParserimport sys reload(sys)sys.setdefaultencoding('UTF-8')# 初始化 ConfigParserupdate_config_parser = ConfigParser.ConfigParser()update_config_parser.read('new_book.info')print "section 信息:",update_config_parser.sections()# 更新作者名称print "原作者:",update_config_parser.get("book","author")# 更改作者姓名为 Jackupdate_config_parser.set("book","author","Jack")print "更改后作者名称:",update_config_parser.get("book","author")# 如果 ematter 节点存在,则删除if update_config_parser.has_section("ematter"): update_config_parser.remove_section("ematter") # 输出信息update_config_parser.write(sys.stdout)# 覆盖原配置文件信息update_config_parser.write(open('new_book.info','w'))

查看原文 >>
相关文章