参考: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 用法

读 配置文件

正常的读配置文件的方法是给 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 ConfigObjconf_ini = "./test.ini"
config = ConfigObj(conf_ini, encoding='UTF8')# 读配置文件
print(config['server'])
print(config['server']['servername'])

运行结果:

创建 配置文件

这里演示一个创建空的 ConfigObj,然后设置文件名、值。最后写入文件

from configobj import ConfigObjconfig = 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'] = section2config['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 内置的读取写入配置文件

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 osos.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 osos.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 osos.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)# 添加sectionif 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")

Python 读写配置文件模块: configobj 和 configParser相关推荐

  1. 读写配置文件模块configparser—参考杨永明博客

    一.configparser模块介绍 1.定义: ConfigParser是用来读取配置文件的包,可对配置文件进行读写操作:如系统中缺乏该模块,可安装包configparser: 2.配置文件的标准格 ...

  2. python读写配置文件使用总结与避坑指南

    最近拿python在写项目部署的相关集成代码,本来两天的工作量,硬是在来回的需求变更中,拖到了一周的时间.今天算是暂时告一段落了.这次由于涉及多个系统的调用和配置参数,代码开发中出现了较多之前未发现或 ...

  3. python 读取配置文件,报错configparser.NoSectionError: No section 解决方案

    configparser简要介绍 python的配置文件,将代码中的配置项抽取到配置文件中,修改配置时不需要涉及到代码修改,方便以后修改参数,极大的方便后期软件的维护.一般配置文件为config.in ...

  4. Python的配置文件模块yaml的使用

    转自:君惜丶 简述 和GNU一样,YAML是一个递归着说"不"的名字.不同的是,GNU对UNIX说不,YAML说不的对象是XML. YAML不是XML. 为什么不是XML呢?因为: ...

  5. python读取配置文件使用_python 使用 ConfigParser 读取和修改INI配置文件

    在程序开发中,使用独立的配置文件来配置一些参数常见且方便,配置文件的解析或修改并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是ConfigParser,ConfigP ...

  6. python读写配置文件

    在写测试脚本时,经常有一些需要变动的数据,可以单独放在ini文件里,然后读取传递给相应的函数,这样程序操作更灵活 这里主要说的就是python使用自带的configparser模块用来读取配置文件,配 ...

  7. python读写excel模块pandas_如何用python pandas操作excel?

    之前跟大家说过关于python处理excel的问题,但是大家反映有些繁琐,大概涉及内容比较多,于是,小编在日常学习中,发现了更简单的方式,现在给大家展示,以便于大家在日后学习里可以方便使用,一起来看下 ...

  8. python读写excel模块pandas_Windows下Python使用Pandas模块操作Excel文件的教程

    安装Python环境ANACONDA是一个Python的发行版本,包含了400多个Python最常用的库,其中就包括了数据分析中需要经常使用到的Numpy和Pandas等.更重要的是,不论在哪个平台上 ...

  9. python读写excel模块pandas_Python Pandas读取修改excel操作攻略

    环境:python 3.6.8 以某米赛尔号举个例子吧: >>> pd.read_excel('1.xlsx', sheet_name='Sheet2') 名字 等级 属性1 属性2 ...

最新文章

  1. Oracle事务处理—隔离级别
  2. SecureRandom
  3. 自己对Delphi中使用正则表达式的研究心得
  4. python精要(73)-turtle(3)
  5. psql error: psql: symbol lookup error: psql: undefined symbol: PQconnectdbParams
  6. jmeterhttp代理服务器_Jmeter使用HTTP代理服务器录制
  7. Python 数据分析三剑客之 Matplotlib(四):线性图的绘制
  8. STL之deque和其他容器
  9. C++11 bind注意事项(传引用参数的时候)
  10. [No000089]String的(补空位)左对齐,(补空位)右对齐
  11. ESRI用户问答精选
  12. 怎么升级计算机的操作系统,电脑如何升级系统版本_Windows10/7电脑升级系统版本的操作步骤...
  13. WEB项目中使用QQ表情
  14. 最新苹果服务器认证,重磅,苹果刷机验证服务器异常(shsh),需要降级的快降级!...
  15. 只有一个文件的开源富文本编辑器,麻雀虽小五脏俱全就是它了
  16. 旁听硕士答辩——爱立信,WireShark,GGSN
  17. 用PS怎样把一个字体居中整个图片
  18. android相机采集sdk,C#用basler相机sdk采集图像并用halcon显示的小程序
  19. 生活:你是如何毁掉生活中的情趣的
  20. 【附源码】计算机毕业设计SSM天气预报系统

热门文章

  1. 领域应用 | 偷偷告诉你,那些二次元萌妹都有个叫知识图谱的爸爸
  2. 一步步手动实现热修复(一)-dex文件的生成与加载
  3. Android官方开发文档Training系列课程中文版:调用相机之控制相机
  4. GCN-Based User Representation Learning for Unifying Robust Recommendation and Fraudster Detection
  5. SIRIM上海,http://www.sirim-global.com
  6. 【译】Immutable.js : 操作 Set -8
  7. 设计模式之——工厂模式
  8. 2014-01-01
  9. Android学习总结00之废话
  10. Hanlp的安装和配置