前言
在做项目的时候一些配置文件都会写在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 #引入模块 "DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' } #类似于操作字典的形式 "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 "htmlcode">import configparser "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模块的资料请关注其它相关文章!
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 【小提琴】陈立新《思乡曲》2004[FLAC+CUE]
- 《战地》新作明年初大规模测试!EA已内部测试一年
- 《GTAOL》PC版时隔多年更新反作弊!小助手宣布跑路
- EA称AI是其业务核心!能提高开发效率、节约成本
- 卫华.1990-太阳升【BMG】【WAV+CUE】
- 呼吸乐队.1992-THEBREATHING【深飞】【WAV+CUE】
- 李玟.2008-1994-2008豪华典藏精选2CD【SONY】【WAV+CUE】
- 《张学友 再现歌神的光辉岁月 梦想成真 2CD》[WAV/分轨][1.2GB]
- 《海来阿木 高音测试王》[WAV+CUE][500MB]
- 《许巍 歌声给你生命的力量 珍藏许巍 3CD》[WAV/分轨][2GB]
- 《直到黎明重制版》配置要求推荐
- 《赛博朋克2077》2.13版本更新内容一览
- 《神话时代:重述版》评测:粉丝们的朝花夕拾
- 战锤40K星际战士2先锋职业介绍|先锋职业技能效果一览
- 战锤40K星际战士2重装职业介绍|重装职业技能效果一览