参考:http://www.voidspace.org.uk/python/configobj.html
Python模块之ConfigParser - 读写配置文件:http://www.cnblogs.com/victorwu/p/5762931.html
Python 官网 configparser 文档:https://docs.python.org/3.7/library/configparser.html
https://pymotw.com/2/ConfigParser/index.html
Python读写配置文件:https://blog.csdn.net/babyfish13/article/details/64919113
正常的读配置文件的方法是给 ConfigObj 一个文件名,然后通过字典来访问成员,子段也是一个字典
from configobj import ConfigObj
config = ConfigObj(filename)
#
value1 = config['keyword1']
value2 = config['keyword2']
#
section1 = config['section1']
value3 = section1['keyword3']
value4 = section1['keyword4']
#
# you could also write
value3 = config['section1']['keyword3']
value4 = config['section1']['keyword4']
初始化的 test.ini文件:
[server]
servername = 192.168.11.1
serverport = 8000
[client_srv]
# 这里是注释
server = localhost
port = 8000
解析文件:
from configobj import ConfigObj
conf_ini = "./test.ini"
config = ConfigObj(conf_ini, encoding='UTF8')
# 读配置文件
print(config['server'])
print(config['server']['servername'])
运行结果:
这里演示一个创建空的 ConfigObj,然后设置文件名、值。最后写入文件
from configobj import ConfigObj
config = ConfigObj()
config.filename = './write_config.ini'
config['keyword1'] = 'value_1'
config['keyword2'] = 'value_2'
config['section1'] = {}
config['section1']['keyword3'] = 'value_3'
config['section1']['keyword4'] = 'value_4'
#
section2 = {
'keyword5': 'value_5',
'keyword6': 'value_6',
'sub-section': {
'keyword7': 'value_7'
}
}
config['section2'] = section2
config['section3'] = {}
config['section3']['keyword 8'] = ['value_8', 'value_9', 'value_10']
config['section3']['keyword 9'] = ['value_11', 'value_12', 'value_13']
config.write()
运行结果:
from configobj import ConfigObj
#
conf_ini = "./test.ini"
config = ConfigObj(conf_ini,encoding='UTF8')
config['server']['servername'] = "127.0.0.1"
config.write()
运行结果:
from configobj import ConfigObj
#
conf_ini = "./test.ini"
config = ConfigObj(conf_ini,encoding='UTF8')
config['new_items'] = {}
config['new_items']['Items1'] = "test items"
config.write()
运行结果:
from configobj import ConfigObj
#
conf_ini = "./test.ini"
config = ConfigObj(conf_ini,encoding='UTF8')
del config['client_srv']['port']
config.write()
运行结果:
from configobj import ConfigObj
#
conf_ini = "./test.ini"
config = ConfigObj(conf_ini,encoding='UTF8')
del config['client_srv']['port']
config.filename = "./test1.ini"
config.write()
configparser 模块 是 Python 内置的读取写入配置的模块。该模块支持读取类似如上格式的配置文件,如 windows 下的 .conf 及 .ini 文件等。
读配置文件
import ConfigParser
cf=ConfigParser.ConfigParser()
cf.read(path) # 读配置文件(ini、conf)返回结果是列表
cf.sections() # 获取读到的所有sections(域),返回列表类型
cf.options('sectionname') # 某个域下的所有key,返回列表类型
cf.items('sectionname') # 某个域下的所有key,value对
value=cf.get('sectionname','key') # 获取某个yu下的key对应的value值
cf.type(value) # 获取的value值的类型
函数说明:
动态写配置文件
cf.add_section('test') # 添加一个域
cf.set('test3','key12','value12') # 域下添加一个key value对
cf.write(open(path,'w')) # 要使用'w'
使用示例
创建两个文件 test.config 及 test.ini 内容及示例截图如下:
[db]
db_port = 3306
db_user = root
db_host = 127.0.0.1
db_pass = xgmtest
[concurrent]
processor = 20
thread = 10
示例代码:
# -*- coding:utf-8 -*-
import configparser
import os
os.chdir("E:\\")
cf = configparser.ConfigParser() # 实例化 ConfigParser 对象
# cf.read("test.ini")
cf.read("test.conf") # 读取文件
# return all section
secs = cf.sections() # 获取sections,返回list
print('sections:', secs, type(secs))
opts = cf.options("db") # 获取db section下的 options,返回list
print('options:', opts, type(opts))
# 获取db section 下的所有键值对,返回list 如下,每个list元素为键值对元组
kvs = cf.items("db")
print('db:', kvs)
# read by type
db_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 int
threads = cf.getint("concurrent", "thread")
processors = cf.getint("concurrent", "processor")
print("db_host:", db_host)
print("db_port:", db_port)
print("db_user:", db_user)
print("db_pass:", db_pass)
print("thread:", threads)
print("processor:", processors)
# 通常情况下,我们已知 section 及 option,需取出对应值,读取方式如下:
# cf.get(...) 返回的会是 str 类型, getint 则返回int类型
# read by type
db_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")
需要配合文件读写函数来写入文件,示例代码如下
import configparser
import os
os.chdir("D:\\Python_config")
cf = configparser.ConfigParser()
# add section / set option & key
cf.add_section("test")
cf.set("test", "count", 1)
cf.add_section("test1")
cf.set("test1", "name", "aaa")
# write to file
with open("test2.ini", "w+") as f:
cf.write(f)
修改和写入类似,注意一定要先 read 原文件!
import configparser
import os
os.chdir("D:\\Python_config")
cf = configparser.ConfigParser()
# modify cf, be sure to read!
cf.read("test2.ini")
cf.set("test", "count", 2) # set to modify
cf.remove_option("test1", "name")
# write to file
with open("test2.ini", "w+") as f:
cf.write(f)
另一示例:
#test.cfg文件内容:
[sec_a]
a_key1 = 20
a_key2 = 10
[sec_b]
b_key1 = 121
b_key2 = b_value2
b_key3 = $r
b_key4 = 127.0.0.1
读配置文件
# -* - coding: UTF-8 -* -
import ConfigParser
#生成config对象
conf = ConfigParser.ConfigParser()
#用config对象读取配置文件
conf.read("test.cfg")
#以列表形式返回所有的section
sections = conf.sections()
print 'sections:', sections #sections: ['sec_b', 'sec_a']
#得到指定section的所有option
options = conf.options("sec_a")
print 'options:', options #options: ['a_key1', 'a_key2']
#得到指定section的所有键值对
kvs = conf.items("sec_a")
print 'sec_a:', kvs #sec_a: [('a_key1', '20'), ('a_key2', '10')]
#指定section,option读取值
str_val = conf.get("sec_a", "a_key1")
int_val = conf.getint("sec_a", "a_key2")
print "value for sec_a's a_key1:", str_val #value for sec_a's a_key1: 20
print "value for sec_a's a_key2:", int_val #value for sec_a's a_key2: 10
#写配置文件
#更新指定section,option的值
conf.set("sec_b", "b_key3", "new-$r")
#写入指定section增加新option和值
conf.set("sec_b", "b_newkey", "new-value")
#增加新的section
conf.add_section('a_new_section')
conf.set('a_new_section', 'new_key', 'new_value')
#写回配置文件
conf.write(open("test.cfg", "w"))
示例代码:
import configparser
# read data from conf file
cf = configparser.ConfigParser()
cf.read("biosver.cfg")
# 返回所有的section
s = cf.sections()
print(s)
# 返回information section下面的option
o1 = cf.options('Information')
print(o1)
# 返回information section下面的option的具体的内容
v1 = cf.items("Information")
print(v1)
# 得到指定项的值
name = cf.get('Information', 'name')
print(name)
# 添加section
if cf.has_section("del"):
print("del section exists")
else:
cf.add_section('del')
cf.set("del", "age", "12")
cf.write(open("biosver.cfg", "w"))
# 删除option
if cf.has_option("del", 'age'):
print("del->age exists")
cf.remove_option("del", "age")
cf.write(open("biosver.cfg", "w"))
print("delete del->age")
else:
print("del -> age don't exist")
# 删除section
if cf.has_section("del1"):
cf.remove_section("del1")
cf.write(open("biosver.cfg", "w"))
else:
print("del1 don't exists")
# modify a value
cf.set("section", "option", "value")