Python 学习 ---> configobj 读写配置文件

ConfigParser 一些问题。

  • 1. 不能区分大小写。
  • 2. 重新写入的 ini 文件不能保留原有 INI 文件的注释。
  • 3. 重新写入的 ini文件不能保持原有的顺序。
  • 4. 不支持嵌套。
  • 5. 不支持格式校验。

所以推荐 configobj 读写配置文件

1、configobj 读写配置文件

读 配置文件

正常的读配置文件的方法是给 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()

2、configParser:读写配置文件

configParser 是 Python 内置

​Python 官网 configparser 文档:https://docs.python.org/3.7/library/configparser.html
Python读写配置文件:https://blog.csdn.net/babyfish13/article/details/64919113

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值的类型

函数说明:

  • (1)getint(section, option):获取section中option的值,返回int类型数据,所以该函数只能读取int类型的值。
  • (2)getboolean(section, option):获取section中option的值,返回布尔类型数据,所以该函数只能读取boolean类型的值。
  • (3)getfloat(section, option):获取section中option的值,返回浮点类型数据,所以该函数只能读取浮点类型的值。
  • (4)has_option(section, option):检测指定section下是否存在指定的option,如果存在返回True,否则返回False。
  • (5)has_section(section):检测配置文件中是否存在指定的section,如果存在返回True,否则返回False。

动态写配置文件

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

基础读取配置文件

  • -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
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")

运行结果截图

基础写入配置文件

  • -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 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"))

ConfigParser 的一些问题:

  • 1. 不能区分大小写。
  • 2. 重新写入的 ini 文件不能保留原有 INI 文件的注释。
  • 3. 重新写入的 ini文件不能保持原有的顺序。
  • 4. 不支持嵌套。
  • 5. 不支持格式校验。

示例代码:

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")

  • 6
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值