打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python3中的configparser模块

configparser模块简介

该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。节与java原先的配置文件相同的格式

看一下configparser生成的配置文件的格式

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

现在看一下类似上方的配置文件是如何生成的

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)	#将对象写入文件

解释一下,操作方式

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

和字典的操作方式相比,configparser模块的操作方式,无非是在实例化的对象后面,跟一个section,在紧跟着设置section的属性(类似字典的形式)

读文件内容

import configparserconfig = configparser.ConfigParser()#---------------------------查找文件内容,基于字典的形式print(config.sections())        #  []config.read('example.ini')print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']print('bytebong.com' in config) # Falseprint('bitbucket.org' in config) # Trueprint(config['bitbucket.org']["user"])  # Atlanprint(config['DEFAULT']['Compression']) #yesprint(config['topsecret.server.com']['ForwardX11'])  #noprint(config['bitbucket.org'])          #<Section: bitbucket.org>for key in config['bitbucket.org']:     # 注意,有default会默认default的键    print(key)print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value

修改

import configparserconfig = configparser.ConfigParser()config.read('example.ini')  #读文件config.add_section('yuan')  #添加sectionconfig.remove_section('bitbucket.org') #删除sectionconfig.remove_option('topsecret.server.com',"forwardx11") #删除一个配置想config.set('topsecret.server.com','k1','11111')config.set('yuan','k2','22222')with open('new2.ini','w') as f:     config.write(f)

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python配置文件解析configparser
Python3 中 configparser 模块解析配置的用法详解
python 操作ini 配置文件大全
python中ConfigParse模块的用法
ssh config配置更新 | 学步园
python常用模块整理
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服