Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python-ConfigParser

python-ConfigParser

作者头像
零式的天空
发布于 2022-03-02 12:14:27
发布于 2022-03-02 12:14:27
58900
代码可运行
举报
文章被收录于专栏:零域Blog零域Blog
运行总次数:0
代码可运行

几乎所有的应用程序真正运行起来的时候,都会读取一个或多个配置文件。 配置文件的作用是:用户不需要修改代码,就可以改变应用程序的行为,让它更好的为应用服务。 本篇主要介绍python中ConfigParser模块的API以及使用示例。

ConfigParser - 解析配置文件

此模块定义类 ConfigParser. 它实现了一个基本的配置文件解析语言,提供一个类似微软INI文件的结构。 使用它可以更容易的被用户自定义。 在python 3.0中ConfigParser 更名为 configparser 配置文件包括由[section] 开头的选项和name: value(name=value)等条目。其中value可以包含格式化字符串。 由’#’ ‘;’开头的行被忽略并作为注释。 在查找配置项时,如果读取的配置项不在指定的section中,将会在[DEFAULT]中查找

RawConfigParser Objects

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
RawConfigParser.defaults()
返回一个包含实例范围默认的字典
RawConfigParser.sections()
返回一个可用section的列表,不包含DEFAULT
RawConfigParser.add_section(section)
增加section
RawConfigParser.has_section(section)
显示是否包含此section
RawConfigParser.options(section)
返回一个在此section中的可用选项的列表
RawConfigParser.has_option(section, option)
如果给定section存在,并包含option,返回True,否则返回False
RawConfigParser.read(filenames)
试图去读并解析一组文件名,返回被成功解析的文件名列表。
RawConfigParser.readfp(fp)
从文件或者类似文件对象中读取配置数据
RawConfigParser.get(section, option)
获取section的option的值
RawConfigParser.getint(section, option) 
            .getfloat(section, option)
            .getboolean(section, option) 可使用0/1 yes/no true/false on/off 将会转化为True, False,其他值
                            会抛出ValueError异常
                            RawConfigParser.items(section)
返回指定section的(name, value)的列表
RawConfigParser.set(section, option, value)
设置选项及值
RawConfigParser.write(fileobject)
将配置信息写入指定文件对象
RawConfigParser.remove_option(section, option)
删除给定section的option
RawConfigParser.remove_section(section)
删除section
RawConfigParser.optionxform(option)
转换option的形式。如更改选项名称为大小写敏感

ConfigParser Objects

ConfigParser 继承自RawConfigParser,并且扩展了它的接口,加入一些可选参数: ConfigParser.get(section, option, raw, vars) 获取给定section的选项值。raw为0,返回转换后的结果,为1返回原始字符形式, vars是一个字典,用来更改选项值 ConfigParser.items(section, option, raw, vars) 返回指定section的(name, value, raw, vars)的列表

代码示例

新建config文件

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import ConfigParser

config = ConfigParser.RawConfigParser()

config.add_section('Section1')
config.set('Section1', 'int', '15')
config.set('Section1', 'bool', 'true')
config.set('Section1', 'float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'wb') as configfile:
    config.write(configfile)

获取config文件内容

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('example.cfg')

# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
float = config.getfloat('Section1', 'float')
int = config.getint('Section1', 'int')
print float + int

# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'bool'):
        print config.get('Section1', 'foo')
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('example.cfg')

# Set the third, optional argument of get to 1 if you wish to use raw mode.
print config.get('Section1', 'foo', 0) # -> "Python is fun!"
print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"

# The optional fourth argument is a dict with members that will take
# precedence in interpolation.
print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
                                                'baz': 'evil'})
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import ConfigParser

# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')

print config.get('Section1', 'foo') # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print config.get('Section1', 'foo') # -> "Life is hard!"

参考文献

python library reference 编写高质量代码:改善Python程序的91个建议

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-06-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
python 配置文件读写
将代码中的配置项抽取到配置文件中,修改配置时不需要涉及到代码修改,避免面对一堆令人抓狂的 magic number,极大的方便后期软件的维护。
orientlu
2018/09/13
1.9K0
python之configparser
configparser用于处理特定格式的文件,其本质上是利用open来操作文件。
菲宇
2019/06/13
3590
ConfigParser:Python中对于ini格式的配置文件的使用
ConfigParser:配置文件的读取 原文链接和公众号 文章链接: http://note.youdao.com/noteshare?id=dfec323b2c6509d7189453ec730b
用户1682544
2018/08/03
2K0
python模块之configparser
上面的demo.ini是一个非常基础的配置文件,它由多个部分(section)组成,每部分包含了带值的选项。ConfigParse类的实例可以对其进行读写操作。
枇杷李子橙橘柚
2022/06/15
1K0
configParser模块详谈
  使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是configParser
py3study
2020/01/16
2.2K0
Python3 中 configpars
configparser 是 Pyhton 标准库中用来解析配置文件的模块,并且内置方法和字典非常接近。Python2.x 中名为 ConfigParser,3.x 已更名小写,并加入了一些新功能。 配置文件的格式如下:
py3study
2020/01/17
4740
Python模块知识8:configparser、压缩模块
一、configparser模块 configparser用于处理特定格式的文件,其本质上是利用open来操作文件。 文件格式如: 1.基本的读取配置文件 -read(filename) 直接读取ini文件内容 -sections() 得到所有的section,并以列表的形式返回 -options(section) 得到该section的所有option -items(section) 得到该section的所有键值对 -get(section,option) 得到section中option的值,返回
企鹅号小编
2018/01/11
7610
Python模块知识8:configparser、压缩模块
python操作conf配置文件——ConfigParser模块
linux的配置文件基本都是config格式的配置文件,所以专门查了一下python操作config的方法,总结记录一下(有时间在总结configobj模块的config格式文件操作方法)
胡齐
2019/10/28
3.7K0
configparser 在python
7.[DEFAULT] [DEFAULT] 一般包含 ini 格式配置文件的默认项,所以 configparser 部分方法会自动跳过这个 section 。 sections() 是获取不到的,还有删除方法对 [DEFAULT] 也无效,但指定删除和修改 [DEFAULT] 里的 keys & values 是可以的,还有个特殊的是,has_section() 也无效,可以和 in 区别使用。
py3study
2020/01/06
4330
python--配置文件以及ConfigParser使用
在项目中通常我们把超参,魔数等需要配置项写入一个配置文件中,方便配置项调整。python项目中通用的配置文件格式有py.ini,json,yml。本文对这些常用形式的配置进行详细讲解。
languageX
2023/01/03
1.6K0
ConfigParser模块教程
配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
幽鸿
2020/04/02
5600
configparser模块
模块简介 该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。 创建文件 来看一个好多软件的常见文档格式如下: [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022
人生不如戏
2018/04/12
6410
Python ConfigParser的
-get(section,option) 得到section中option的值,返回为string类型
py3study
2020/01/13
7040
Python中12个常用模块的使用教程
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
Python学习者
2022/12/08
1.2K0
python configparser模块
['bitbucket.org', 'topsecret.server.com']
py3study
2018/08/02
4480
常用模块补充,内置函数,异常处理
shutil.copyfileobj(fsrc, fdst[, length]) 将文件内容拷贝到另一个文件中
py3study
2020/01/19
1.7K0
常用模块补充,内置函数,异常处理
python的 ConfigParser
ConfigParser模块是python自带的读取配置文件的模块.通过他可以方便的读取配置文件. 这篇文章简单介绍一下读取配置文件的方法. 配置文件.顾名思议就是存放配置的文件.下面是个例子 [info] age = 21 name = chen sex = male 其中[ ] 中的info是这段配置的名字 下面age,name都是属性 下面的代码演示了如何读取配置文件.和修改配置中变量的值 from __future__ import with_statement im
py3study
2020/01/14
5070
Python configparser标准库简介
如果你要使用Python处理类似ini这种格式的文件,那么肯定离不开configparser标准库,它使用起来很简单而且非常方便。下面就让我们来看看吧。
乐百川
2020/03/25
7740
ini配置文件操作方法
一、ini文件介绍 ini配置文件常用于存储项目全局变量 如:接口地址、输出文件路径、项目地址、用户名、密码等 二、ini文件编写格式 [节点] 选项=选项值 ;表示注释 注意:节点名不可以重复【所以写入新节点前要判断是否存在】 三、.ini 文件读取 1、.ini文件读 import configparser config = configparser.ConfigParser() config.read('config.ini') # 获取所有节点 sec = config.sections() pr
孟船长
2022/04/12
1.6K0
相关推荐
python 配置文件读写
更多 >
LV.1
这个人很懒,什么都没有留下~
加入讨论
的问答专区 >
KOL擅长5个领域
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
    本文部分代码块支持一键运行,欢迎体验
    本文部分代码块支持一键运行,欢迎体验