@hainingwyx
2018-09-08T13:59:05.000000Z
字数 2272
阅读 1835
python
Python 读取写入配置文件很方便,可使用内置的 configparser 模块。该模块支持读取配置文件,如 windows 下的 .conf 及 .ini 文件等。
例如:
[db]db_port = 3306db_user = rootdb_host = 127.0.0.1db_pass = xgmtest[concurrent]processor = 20thread = 10
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() 函数。
示例代码
# !/usr/bin/env python# -*- coding:utf-8 -*-import ConfigParserimport osos.chdir("D:\\Python_config")cf = ConfigParser.ConfigParser()# cf.read("test.ini")cf.read("test.conf")#return all sectionsecs = cf.sections()print 'sections:', secs, type(secs)opts = cf.options("db")print 'options:', opts, type(opts)kvs = cf.items("db")print 'db:', kvs#read by typedb_host = cf.get("db", "db_host")db_port = cf.getint("db", "db_port")db_user = cf.get("db", "db_user")db_pass = cf.get("db", "db_pass")#read intthreads = cf.getint("concurrent", "thread")processors = cf.getint("concurrent", "processor")print "db_host:", db_hostprint "db_port:", db_portprint "db_user:", db_userprint "db_pass:", db_passprint "thread:", threadsprint "processor:", processorsConfigParser
write(fp) 将config对象写入至某个 .init 格式的文件 Write an .ini-format representation of the configuration state.
add_section(section) 添加一个新的section
set( section, option, value ) 对section中的option进行设置,需要调用write将内容写入配置文件 ConfigParser2
remove_section(section) 删除某个 section
remove_option(section, option) 删除某个 section 下的 option
示例代码
import ConfigParserimport osos.chdir("D:\\Python_config")cf = ConfigParser.ConfigParser()# add section / set option & keycf.add_section("test")cf.set("test", "count", 1)cf.add_section("test1")cf.set("test1", "name", "aaa")# write to filewith open("test2.ini","w+") as f:cf.write(f)ConfigParser2
配置文件的语法比python源文件更自由
prefix=/usr/localprefix: /usr/local
两者等效。
配置文件中的名字不区分大小写
>>> cfg.get('installation','PREFIX')'/usr/local'>>> cfg.get('installation','prefix')'/usr/local'>>>
getboolean()查找任何可行的值
log_errors = truelog_errors = TRUElog_errors = Yeslog_errors = 1
以上等价
配置文件整体读取
[installation]library=%(prefix)s/libinclude=%(prefix)s/includebin=%(prefix)s/binprefix=/usr/local
prefix定义在之前之后无影响
能一次读取多个配置文件然后合并成一个配置,变量的改写采取的是后发制人策略,以最后一个为准。
https://www.cnblogs.com/feeland/p/4514771.html
https://python3-cookbook.readthedocs.io/zh_CN/latest/c13/p10_read_configuration_files.html