Python ConfigParser模块的使用示例

前言

在做项目的时候一些配置文件都会写在settings配置文件中,今天在研究"州的先生"开源文档写作系统-MrDoc的时候,发现部分配置文件写在config.ini中,并利用configparser进行相关配置文件的读取及修改。

一、ConfigParser模块简介

该模块适用于配置文件的格式与windows ini文件类似,是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。格式如下:

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

括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。

二、ConfigParser模块使用

1.写入操作

代码如下:

import configparser #引入模块
​
config = configparser.ConfigParser()  #类中一个方法 #实例化一个对象
​
config["DEFAULT"] = {'ServerAliveInterval': '45',
           'Compression': 'yes',
           'CompressionLevel': '9',
           'ForwardX11':'yes'
           } #类似于操作字典的形式
​
config['bitbucket.org'] = {'User':'Atlan'} #类似于操作字典的形式
​
config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
​
with open('example.ini', 'w') as configfile:
​
  config.write(configfile) #将对象写入文件
以上代码做个简单的解释,和字典的操作方式相比,configparser模块的操作方式,无非是在实例化的对象后面,跟一个section,在紧跟着设置section的属性(类似字典的形式)

config["DEFAULT"] = {'ServerAliveInterval': '45',
           'Compression': 'yes',
           'CompressionLevel': '9',
           'ForwardX11':'yes'
           } #类似于操作字典的形式
#config后面跟的是一个section的名字,section的段的内容的创建类似于创建字典。类似与字典当然还有别的操作方式啦!
config['bitbucket.org'] = {'User':'Atlan'} #类似于最经典的字典操作方式

2.读取操作

import configparser
config = configparser.ConfigParser()
#---------------------------查找文件内容,基于字典的形式
print(config.sections())    # []
config.read('example.ini',encoding='utf-8')
print(config.sections())    #  ['bitbucket.org', 'topsecret.server.com']
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True
print('DEFAULT' in config) # True
print(config['bitbucket.org']["user"]) # Atlan
​
print(config['DEFAULT']['Compression']) #yes
print(config['topsecret.server.com']['ForwardX11']) #no
​
print(config['bitbucket.org'])     #<Section: bitbucket.org>
for key in config['bitbucket.org']:   # 注意,有default会默认default的键
  print(key)             #user serveraliveinterval compression compressionlevel forwardx11
​
# 同for循环,找到'bitbucket.org'下所有键 ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
print(config.options('bitbucket.org'))
​
print(config.items('bitbucket.org'))  #找到'bitbucket.org'下所有键值对 [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'Atlan')]
​
print(config.get('bitbucket.org','compression')) # yes    get方法Section下的key对应的value
print(config.getboolean('bitbucket.org','compression')) # True

3.修改操作

import configparser
​
config = configparser.ConfigParser()
​
config.read('example.ini',encoding='utf-8') #读文件
​
config.add_section('yuan') #添加section
​
config.remove_section('bitbucket.org') #删除section
config.remove_option('topsecret.server.com',"forwardx11") #删除一个配置项
# 修改某个option的值,如果不存在该option 则会创建
config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
#写回文件
config.write(open("example.ini", "w"))
# 写到其他文件
with open('new2.ini','w') as f:
   config.write(f)

以上就是Python ConfigParser模块的使用示例的详细内容,更多关于Python ConfigParser模块的资料请关注我们其它相关文章!

(0)

相关推荐

  • Python中的ConfigParser模块使用详解

    1.基本的读取配置文件 -read(filename) 直接读取ini文件内容 -sections() 得到所有的section,并以列表的形式返回 -options(section) 得到该section的所有option -items(section) 得到该section的所有键值对 -get(section,option) 得到section中option的值,返回为string类型 -getint(section,option) 得到section中option的值,返回为int类型,

  • Python configparser模块封装及构造配置文件

    1.configparser模块简介 使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情的库,那就是configParser configParser解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项 2.看一下configparser生成的配置文件的格式 ini配置文件格式如下: 这里是注释 [log] log_path = base_dir

  • 详解Python读取配置文件模块ConfigParser

    1,ConfigParser模块简介 假设有如下配置文件,需要在Pyhton程序中读取 $ cat config.ini [db] db_port = 3306 db_user = root db_host = 127.0.0.1 db_pass = xgmtest [SectionOne] Status: Single Name: Derek Value: Yes Age: 30 Single: True [SectionTwo] FavoriteColor = Green [SectionT

  • python解析模块(ConfigParser)使用方法

    测试配置文件test.conf内容如下: 复制代码 代码如下: [first]w = 2v: 3c =11-3 [second] sw=4test: hello 测试配置文件中有两个区域,first和second,另外故意添加一些空格.换行. 下面解析: 复制代码 代码如下: >>> import ConfigParser>>> conf=ConfigParser.ConfigParser()>>> conf.read('test.conf')['te

  • Python configparser模块应用过程解析

    一.configparser模块是什么 可以用来操作后缀为 .ini 的配置文件: python标准库(就是python自带的意思,无需安装) 二.configparser模块基本使用 2.1 读取 ini 配置文件 #存在 config.ini 配置文件,内容如下: [DEFAULT] excel_path = ../test_cases/case_data.xlsx log_path = ../logs/test.log log_level = 1 [email] user_name = 3

  • Python自动化测试ConfigParser模块读写配置文件

    Python自动化测试ConfigParser模块读写配置文件 ConfigParser 是Python自带的模块, 用来读写配置文件, 用法及其简单. 直接上代码,不解释,不多说. 配置文件的格式是: []包含的叫section,    section 下有option=value这样的键值 配置文件   test.conf    [section1] name = tank age = 28 [section2] ip = 192.168.1.1 port = 8080 Python代码 #

  • Python使用自带的ConfigParser模块读写ini配置文件

    在用Python做开发的时候经常会用到数据库或者其他需要动态配置的东西,硬编码在里面每次去改会很麻烦.Python自带有读取配置文件的模块ConfigParser,使用起来非常方便. ini文件 ini配置文件格式: 读取配置文件: import ConfigParser conf = ConfigParser.ConfigParser() conf.read('dbconf.ini') # 文件路径 name = conf.get("section1", "name&quo

  • Python配置文件解析模块ConfigParser使用实例

    一.ConfigParser简介 ConfigParser 是用来读取配置文件的包.配置文件的格式如下:中括号"[ ]"内包含的为section.section 下面为类似于key-value 的配置内容. 复制代码 代码如下: [db]  db_host = 127.0.0.1  db_port = 22  db_user = root  db_pass = rootroot    [concurrent]  thread = 10  processor = 20 中括号"

  • Python ConfigParser模块的使用示例

    前言 在做项目的时候一些配置文件都会写在settings配置文件中,今天在研究"州的先生"开源文档写作系统-MrDoc的时候,发现部分配置文件写在config.ini中,并利用configparser进行相关配置文件的读取及修改. 一.ConfigParser模块简介 该模块适用于配置文件的格式与windows ini文件类似,是用来读取配置文件的包.配置文件的格式如下:中括号"[ ]"内包含的为section.section 下面为类似于key-value 的配置

  • Python random模块的使用示例

    常用的 random 模块方法 import random # random.random()用于生成一个 0 到 1 的随机浮点数: 0 <= n < 1.0 print(random.random()) # 0.18246795790915304 # random.randint(a, b),用于生成一个指定范围内的整数. # 其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b print(random.randint(1, 10)) # 8 # rand

  • Python datetime模块的使用示例

    1.获取当前年月日时分秒 # -*- encoding=utf-8 -*- import datetime now = datetime.datetime.now() print("now:{}".format(now)) year = now.year print("year:{}".format(year)) month = now.month print("month:{}".format(month)) day = now.day pri

  • Python hashlib模块的使用示例

    一.hashlib模块 用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 :SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法. 1.使用hashlib模块进行MD5加密. import hashlib m = hashlib.md5() m.update(b"Hello") m.update(b"It's me") print(m.hexdigest()) m.update(b"It's been a long

  • Python paramiko模块的使用示例

    paramiko模块提供了ssh及sft进行远程登录服务器执行命令和上传下载文件的功能.这是一个第三方的软件包,使用之前需要安装. 1 基于用户名和密码的 sshclient 方式登录 # 建立一个sshclient对象 ssh = paramiko.SSHClient() # 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 调用c

  • Python configparser模块配置文件过程解析

    ConfigParser模块在Python3修改为configparser,这个模块定义了一个ConfigeParser类,该类的作用是让配置文件生效.配置文件的格式和window的ini文件相同 编辑配置文件: .ini 模板:内容自定义 一. 编辑配置文件 import configparser config = configparser.ConfigParser() config['DEFAULT'] = { 'ServerAliveInterval':'45', 'Compression

  • Python configparser模块常用方法解析

    ConfigParser模块在python中用来读取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一个或多个节(section), 每个节可以有多个参数(键=值).使用的配置文件的好处就是不用在程序员写死,可以使程序更灵活. 注意:在python 3 中ConfigParser模块名已更名为configparser configparser函数常用方法: 读取配置文件: read(filename) #读取配置文件,直接读取ini文件内容 sections() #获取i

  • Python pluggy模块的用法示例演示

    目录 1 pluggy 简介 2 安装 3 使用初体验 4 详解解释 5 HookspeckMarker装饰器支持传入一些特定的参数 6 HookImplMarker装饰器也支持传入一些特定的参数 1 pluggy 简介 pluggy 作用:提供了一个简易便捷的插件系统,可以做到插件与主题功能松耦合 pluggy 是pytest,tox,devpi的核心框架 2 安装 执行如下命令即可 pip install pluggy 3 使用初体验 import pluggy # HookspecMark

随机推荐