Python 操作配置文件

Lan
Lan
2020-03-15 / 0 评论 / 662 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2020年03月15日,已超过1475天没有更新,若内容或图片失效,请留言反馈。

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

文件格式

  • 配置文件中包含一个或多个 section,每个 section 都有自己的 option;

  • section 用 [sect_name] 表示,每个 option 是一个键值对,使用分隔符 = 或者 : 隔开;

  • option 分隔符两端的空格会被忽略掉;

  • 配置文件使用 # 注释;

示例配置文件 dbconf.cfg;

[dbconfig]# 数据库读库链接信息host=127.0.0.1user=root
passwd=root
database=banma_finance
port=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 Jack
dbconfig
  host = 127.0.0.1
  user = root
  passwd = root
  database = banma_finance
  port = 3306

配置文件的写入

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

# !/usr/bin/python
# coding:utf-8
import ConfigParser 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 sysreload(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'))




0

评论 (0)

取消