小白的Python之路 day5 configparser模块的特点和用法
2018-01-25 22:06
309 查看
configparser模块的特点和用法
一、概述
主要用于生成和修改常见配置文件,当前模块的名称在 python 3.x 版本中变更为 configparser。在python2.x版本中为ConfigParser
二、格式
常见配置文件格式如下:[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no
三、主要用法
1、创建配置文件
import configparser #导入configparser模块 #生成一个对象 config = configparser.ConfigParser() #配置默认全局配置组 config["DEFALUT"] = {"ServerAliveInterval":"45", "Compression":"yes", "CompressionLevel":"9" } #配置第一个其他组 config["bitbucket.org"] = {} #直接赋值 config["bitbucket.org"]["User"] = 'hg' #配置第二个其他组 config["topsecret.server.com"] = {} #这边就赋给一个变量 topsecret = config["topsecret.server.com"] #通过变量赋值 topsecret["Host Port"] = '50022' topsecret["ForwardX11"] = 'no' #给全局配置组赋值 config["DEFALUT"]["ForwardX11"] = "yes" #操作完毕,把配置的内容写入一个配置文件中 with open("example.ini","w") as configfile: config.write(configfile)
2、读取配置文件
1)、读取配置组>>> import configparser >>> config = configparser.ConfigParser() >>> config.sections() #不读取配置文件,组名列表为空 [] >>> config.read("example.ini") #读取配置文件,返回配置文件名 ['example.ini'] >>> config.sections() #返回除默认配置组的其他组名 ['bitbucket.org', 'topsecret.server.com'] >>> config.defaults() #读取默认配置组,并返回有序字典 OrderedDict([('compressionlevel', '9'), ('serveraliveinterval', '45'), ('compression', 'yes'), ('forwardx11', 'yes')])
2)、组名是否存在
>>> 'bitbucket.org' in config #组名存在 True >>> 'zhangqigao.org' in config #组名不存在 False
3)、读取组内的值
>>> config["bitbucket.org"]["User"] #读取"bitbucket.org"配置组中的值 'hg' >>> config["DEFAULT"]["Compression"] #读取默认配置组中的值 'yes' >>> topsecret = config['topsecret.server.com'] #把配置组赋给一个对象 >>> topsecret['ForwardX11'] #通过对象获取值
4)、 循环获取组内的key值
>>> for key in config["bitbucket.org"]: #循环打印bitbucket.org组下的key值 ... print(key) ... #输出,只打印默认组和bitbucket.org组的key值 user compressionlevel serveraliveinterval compression forwardx11 >>> for key in config["topsecret.server.com"]:#循环打印topsecret.server.com组下的key值 ... print(key) ... #输出,只打印默认组和topsecret.server.com组的key值 host port forwardx11 compressionlevel serveraliveinterval compression
重点:
四、configparser增删改查语法
1、配置文件名i.cfg①删除section和option
相关文章推荐
- 小白的Python之路 day5 模块XML特点和用法
- 小白的Python之路 day5 shelve模块讲解
- 小白的Python之路 day5 python模块详解及import本质
- 小白的Python之路 day5 os,sys模块详解
- Python之路,Day5 - Python基础5
- python小白-day5 模块
- Python3内置模块详解1 (Python 之路 Day5 - 常用模块学习 )
- python小白-day5 time&datetime模块
- 运维小白的python之路(五)——模块
- python中configParser模块的基础用法
- Python小白学习之路(四)——第一次练习题
- Python小白学习之路(十四)—【作用域】【匿名函数】【编程方法论】【高阶函数】
- python小白-day5 json&pickle
- 【小白笔记】python web学习之路-Flask(1)
- 小白的Python之路 day4 迭代器
- 运维小白的Python之路(二)
- 小白的Python之路 day4 生成器
- Python小白学习之路(八)—【变量】【基本数据类型分类】【集合】【集合的功能】
- Python学习利器——我的小白 Anaconda安装之路
- Python小白学习之路(二)—【Pycharm安装与配置】【创建项目】【运算符】【数据类型】