Python ConfigParser模块的使用示例
作者:小张学Python 发布时间:2023-12-02 03:35:15
标签: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)
来源:https://www.cnblogs.com/xiaozhangpython/archive/2020/10/12/13802535.html


猜你喜欢
- 最近在调代码,碰到幂函数、指数函数,总是提示ValueError: math domain errorValueError: negativ
- 前言虽然各种编程语言之间大部分语法存在共通的地方,但是在一些细节的处理上还是千差万别才接触Python不久(之前是学Java的),实在想吐槽
- 什么是Firebug从事了数年的Web开发工作,越来越觉得现在对WEB开发有了更高的要求。要写出漂亮的HTML代码;要编写精致的CSS样式表
- 这篇文章主要介绍了python调用接口的4种方式代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的
- Javascript有许多内建的方法来产生对话框,如:window.alert(), window.confirm(),window.pro
- 了兑现我对大家的承诺,我们现在立即就将“借助数据库和ASP程序”编写出来的,可以同时适用于IIS和P
- pytorch加载图片数据集有两种方法。1.ImageFolder 适合于分类数据集,并且每一个类别的图片在同一个文件夹, ImageFol
- 前言在python中, 切片是一个经常会使用到的语法, 不管是元组, 列表还是字符串, 一般语法就是:sequence[ilow:ihigh
- 2008北京奥运会块到了,下面的js代码将告诉你,离奥运会开幕还要多少天!让我们一起迎接这美好的时刻。相关文章推荐:各种北京2008奥运会倒
- 目录1图像叠加2图像融合3按位操作1图像叠加可以通过OpenCV函数cv.add()或简单地通过numpy操作添加两个图像,res = im
- 本文实例讲述了Python原始字符串(raw strings)用法,分享给大家供大家参考。具体如下: Python原始字符串的产生
- Tip:本文仅供学习与交流,切勿用于非法用途!!!背景介绍有个同学问我:“XXX,有没有办法搜集一下淘宝的商品信息啊,我想要做个统计”。于是
- 相对或者绝对import 更多的复杂部分已经从python2.5以来实现:导入一个模块可以指定使用绝对或者包相对的导入。这个计划将移动到使绝
- Python 实现删除某路径下文件及文件夹的脚本#!/usr/bin/env pythonimport osimport shutildel
- PHP使用Swagger生成好看的API文档不是不可能,而是非常简单。首先本人使用Laravel框架,所以在Laravel上安装swagge
- 1:文件内容格式为json的数据如何解析import json,os,syscurrent_dir=os.path.abspath(&quo
- 上一课:ACCESS入门教程:窗口和菜单的使用向导简介 这一课我们要建立一个客户订单管理数据库,这个数据库将用ACCESS提供的数据库向导来
- MySQL数据库线程缓冲池的相关知识是本文我们主要要介绍的内容,MySQL数据库支持线程缓存,在多线程连接模式下,如果连接断开后,将这个线程
- 脚手架(vue-cli)(一)什么是脚手架概念:是一种用于快速开发Vue项目的系统架构优点:能够帮助咱们快速的开发项目缺点:由于脚手架适用于
- 配置指令如下:[opcache]zend_extension=opcache.soopcache.enable_cli=1;共享内存大小,