当前位置: 首页 > 编程笔记 >

Python ConfigParser模块的使用示例

皮景龙
2023-03-14
本文向大家介绍Python ConfigParser模块的使用示例,包括了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模块的资料请关注小牛知识库其它相关文章!

 类似资料:
  • 本文向大家介绍Python hashlib模块的使用示例,包括了Python hashlib模块的使用示例的使用技巧和注意事项,需要的朋友参考一下 一.hashlib模块 用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 :SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法。 1.使用hashlib模块进行MD5加密。 注:hashlib.md5():创

  • 本文向大家介绍Python中atexit模块的基本使用示例,包括了Python中atexit模块的基本使用示例的使用技巧和注意事项,需要的朋友参考一下 atexit模块很简单,只定义了一个register函数用于注册程序退出时的回调函数,我们可以在这个回调函数中做一些资源清理的操作。 注:如果程序是非正常crash,或者通过os._exit()退出,注册的回调函数将不会被调用。 我们也可以通过sy

  • 1、import Python 模块的使用跟其他编程语言也是类似的。你要使用某个模块,在使用之前,必须要导入这个模块。导入模块我们使用关键字 import。 import 的语法基本如下: import module1[, module2[,... moduleN] 比如我们使用标准库模块中的 math 模块。当解释器遇到 import 语句,如果模块在当前的搜索路径就会被导入。 #!/usr/

  • 本文向大家介绍Python的collections模块中namedtuple结构使用示例,包括了Python的collections模块中namedtuple结构使用示例的使用技巧和注意事项,需要的朋友参考一下 namedtuple 就是命名的 tuple,比较像 C 语言中 struct。一般情况下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能按

  • 你会对自己编写的 Puppet 代码感到羞愧吗?其他人看你的代码时会有恐惧感吗? 为了使你的 Puppet 配置清单更清晰且易于维护,一件最重要的事情就是将这些配置清单组织成 模块(modules)。 模块是对相关事物进行分组的一种简单方式;例如,一个 webserver 模块可能包含作为一个 Web 服务器所需的一切,包括 Apache 配置文件,虚拟主机配置模板以及部署这些所需的 Puppet

  • Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用。 我们以内建的sys模块为例,编写一个hello的模块: #!/usr/bin/env python # -*- coding: utf-8 -*- ' a test module ' __author__ = 'Michael Liao' import sys def test(): args =

  • Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用。 我们以内建的sys模块为例,编写一个hello的模块: #!/usr/bin/env python3 # -*- coding: utf-8 -*- ' a test module ' __author__ = 'Michael Liao' import sys def test(): args =

  • 本文向大家介绍Node.js readline模块与util模块的使用,包括了Node.js readline模块与util模块的使用的使用技巧和注意事项,需要的朋友参考一下 1. 使用readline模块逐行读取流数据 1.1. 创建Interface对象 在readline模块中,通过Interface对象的使用来实现逐行读取流数据的处理。因此首先要创建Interface对象,在readlin