转自博客:https://blog.csdn.net/shortwall/article/details/78615

configparser 简介

configparser 是 Pyhton 标准库中用来解析配置文件的模块,并且内置方法和字典非常接近。Python2.x 中名为 ConfigParser,3.x 已更名小写,并加入了一些新功能。 
配置文件的格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes [bitbucket.org]
User = Tom [topsecret.com]
Port: 50022
ForwardX11: no

 “[ ]”包含的为 section,section 下面为类似于 key - value 的配置内容; 
configparser 默认支持 ‘=’ ‘:’ 两种分隔。

configparser 常用方法

初始化实例

使用 configparser 首先需要初始化实例,并读取配置文件:

>>> import configparser
>>> config = configparser.ConfigParser() # 注意大小写
>>> config.read("config.ini") # 配置文件的路径
["config.ini"]

  或者可以直接读字典

>>> parser = configparser.ConfigParser()
>>> parser.read_dict({'section1': {'key1': 'value1',
... 'key2': 'value2',
... 'key3': 'value3'},
... 'section2': {'keyA': 'valueA',
... 'keyB': 'valueB',
... 'keyC': 'valueC'},
... 'section3': {'foo': 'x',
... 'bar': 'y',
... 'baz': 'z'}
... })

  

获取所有 sections

>>> config.sections()
['bitbucket.org', 'topsecret.com'] # 注意会过滤掉[DEFAULT]

获取指定 section 的 keys & values

>>> config.items('topsecret.com')
>>>> [('port', '50022'), ('forwardx11', 'no')] # 注意items()返回的字符串会全变成小写

获取指定 section 的 keys

>>> config.options('topsecret.com')
['Port', 'ForwardX11']

  

>>> for option in config['topsecret.com']:
... print(option)
Port
ForwardX11

获取指定 key 的 value

>>> config['bitbucket.org']['User']
'Tom'

  

>>> config.get('bitbucket.org', 'User')
'Tom'
>>> config.getint('topsecret.com', 'Port')
50022

检查

>>> 'DEFAULT' in config
True
>>> 'test' in config['section_test']
False
>>> 'Tom' in config['bitbucket.org']['User']
True

  

>>> config.has_section('bitbucket.org')
True
>>> config.has_option('section_test', 'test')
False

添加

>>> config.add_section('Section_1')
>>> config.set('Section_1', 'key_1', 'value_1') # 注意键值是用set()方法
>>> config.write(open('config.ini', 'w')) # 一定要写入才生效

删除

>>> config.remove_option('Section_1', 'key_1')
True
>>> config.remove_section('Section_1')
True
>>> config.clear() # 清空除[DEFAULT]之外所有内容
>>> config.write(open('config.ini', 'w'))

关于 [DEFAULT]

[DEFAULT] 一般包含 ini 格式配置文件的默认项,所以 configparser 部分方法会自动跳过这个 section 。 
前面已经提到 sections() 是获取不到的,还有删除方法对 [DEFAULT] 也无效:

>>> config.remove_section('DEFAULT')
False
>>> config.clear()
>>> 'DEFAULT' in config
True
>>> 'ForwardX11' in config['DEFAULT']
True
>>> config.sections()
[]

  但指定删除和修改 [DEFAULT] 里的 keys & values 是可以的:

>>> config.remove_option('DEFAULT', 'ForwardX11')
True
>>> config.set('DEFAULT', 'ForwardX11','no')
>>> config['DEFAULT']['ForwardX11']
'no'

  还有个特殊的是,has_section() 也无效,可以和 in 区别使用:

>>> config.has_section('DEFAULT')
False
>>> 'DEFAULT' in config
True

  

>>> config.has_section('bitbucket.org') True>>> config.has_option('section_test', 'test') False

Python3 中 configparser 模块用法的更多相关文章

  1. Python3 中 configparser 模块解析配置的用法详解

    configparser 简介 configparser 是 Pyhton 标准库中用来解析配置文件的模块,并且内置方法和字典非常接近.Python2.x 中名为 ConfigParser,3.x 已 ...

  2. Python3中正则模块re.compile、re.match及re.search函数用法详解

    Python3中正则模块re.compile.re.match及re.search函数用法 re模块 re.compile.re.match. re.search 正则匹配的时候,第一个字符是 r,表 ...

  3. python中hashlib模块用法示例

    python中hashlib模块用法示例 我们以前介绍过一篇Python加密的文章:Python 加密的实例详解.今天我们看看python中hashlib模块用法示例,具体如下. hashlib ha ...

  4. python中argparse模块用法实例详解

    python中argparse模块用法实例详解 这篇文章主要介绍了python中argparse模块用法,以实例形式较为详细的分析了argparse模块解析命令行参数的使用技巧,需要的朋友可以参考下 ...

  5. python中confIgparser模块学习

    python中configparser模块学习 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section ...

  6. python中MySQLdb模块用法实例

    篇文章主要介绍了python中MySQLdb模块用法,以实例形式详细讲述了MySQLdb模块针对MySQL数据库的各种常见操作方法,非常具有实用价值,需要的朋友可以参考下 本文实例讲述了python中 ...

  7. Python中ConfigParser模块应用

    Python中ConfigParser模块应用 Python的ConfigParser模块定义了3个对INI文件进行操作的类 RawConfigParser.ConfigParser和SafeConf ...

  8. python中configparser模块读取ini文件

    python中configparser模块读取ini文件 ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(se ...

  9. python3 之configparser 模块

    configparser 简介 configparser 是 Pyhton 标准库中用来解析配置文件的模块,并且内置方法和字典非常接近[db]db_count = 31 = passwd2 = dat ...

随机推荐

  1. ansible 安装 使用 命令 笔记 生成密钥 管控机 被管控机 wget epel源

      ansible 与salt对比 相同 都是为了同时在多台机器上执行相同的命令 都是python开发 不同 agent(saltstack需要安装.ansible不需要) 配置(salt配置麻烦,a ...

  2. STL 最大堆与最小堆

    在第一场CCCC选拔赛上,有一关于系统调度的水题.利用优先队列很容易AC. // 由于比赛时花费了不少时间研究如何定义priority_queue的比较函数,决心把STL熟练掌握... Queue 首 ...

  3. java — 抽象类和接口

    老生常谈的一个概念,很明确,不过我们多从几个角度来看下应该会有更好的理解,最近翻了下java8的某些新特性 关于接口的新特性让笔者受惊了,下面结合下做个总结,有更新的话直接在这里更新. 设计层面讲: ...

  4. @RestControllerAdvice作用及原理

    原文:Spring Boot 系列(八)@ControllerAdvice 拦截异常并统一处理 在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@Exceptio ...

  5. ElasticSearch入门介绍之会当凌绝顶(一)

    ElasticSearch也是一款非常优秀的开源的全文检索框架,以大名鼎鼎的Apache Lucene为基础,高度封装了更丰富,易用的API,同时与Apache Solr一样,提供了非常强大的分布式集 ...

  6. 利用jQuery获取jsonp

    前端js代码: $.ajax({ url: 'http://localhost:8080/webApp/somejsonp', dataType: "jsonp", jsonp: ...

  7. conan本地安装包

    在远程有的情况下,本地没有的情况下,执行命令 conan install package/版本号@usr/stable ,比如conan install opencv/3.4.3@seal/stabl ...

  8. vue.js_05_vue.js的过滤器

    1.过滤器的定义和使用 实现:将页面的中的单纯替换成,用户传来的文字. 全局过滤器:所有的Vue对象都可以使用 <body> <div id="app"> ...

  9. PAT甲级——A1018 Public Bike Management

    There is a public bike service in Hangzhou City which provides great convenience to the tourists fro ...

  10. mysql不创建表 <property name="hbm2ddl.auto">update</property> 无效

    netbeans win10 mysql8 hibernate 4.3.11 dakai mysql的general_log发现并没有创建表的语句 未完待续 今天又遇到不创建表的问题 但是问题比较奇怪 ...