详解Python利用configparser对配置文件进行读写操作
简介
想写一个登录注册的demo,但是以前的demo数据都写在程序里面,每一关掉程序数据就没保存住。。
于是想着写到配置文件里好了
Python自身提供了一个Module-configparser,来进行对配置文件的读写
Configurationfileparser.
Aconfigurationfileconsistsofsections,leadbya“[section]”header,
andfollowedby“name:value”entries,withcontinuationsandsuchin
thestyleofRFC822.
NoteTheConfigParsermodulehasbeenrenamedtoconfigparserinPython3.The2to3toolwillautomaticallyadaptimportswhenconvertingyoursourcestoPython3.
在py2中,该模块叫ConfigParser,在py3中把字母全变成了小写。本文以py3为例
类
ConfigParser的属性和方法
ConfigParser--responsibleforparsingalistof configurationfiles,andmanagingtheparseddatabase. methods: __init__(defaults=None,dict_type=_default_dict,allow_no_value=False, delimiters=('=',':'),comment_prefixes=('#',';'), inline_comment_prefixes=None,strict=True, empty_lines_in_values=True,default_section='DEFAULT', interpolation=,converters= ): Createtheparser.When`defaults'isgiven,itisinitializedintothe dictionaryorintrinsicdefaults.Thekeysmustbestrings,thevalues mustbeappropriatefor%()sstringinterpolation. When`dict_type'isgiven,itwillbeusedtocreatethedictionary objectsforthelistofsections,fortheoptionswithinasection,and forthedefaultvalues. When`delimiters'isgiven,itwillbeusedasthesetofsubstrings thatdividekeysfromvalues. When`comment_prefixes'isgiven,itwillbeusedasthesetof substringsthatprefixcommentsinemptylines.Commentscanbe indented. When`inline_comment_prefixes'isgiven,itwillbeusedasthesetof substringsthatprefixcommentsinnon-emptylines. When`strict`isTrue,theparserwon'tallowforanysectionoroption duplicateswhilereadingfromasinglesource(file,stringor dictionary).DefaultisTrue. When`empty_lines_in_values'isFalse(default:True),eachemptyline markstheendofanoption.Otherwise,internalemptylinesof amultilineoptionarekeptaspartofthevalue. When`allow_no_value'isTrue(default:False),optionswithout valuesareaccepted;thevaluepresentedfortheseisNone. When`default_section'isgiven,thenameofthespecialsectionis namedaccordingly.Bydefaultitiscalled``"DEFAULT"``butthiscan becustomizedtopointtoanyothervalidsectionname.Itscurrent valuecanberetrievedusingthe``parser_instance.default_section`` attributeandmaybemodifiedatruntime. When`interpolation`isgiven,itshouldbeanInterpolationsubclass instance.Itwillbeusedasthehandlerforoptionvalue pre-processingwhenusinggetters.RawConfigParserobjectsdon'tdo anysortofinterpolation,whereasConfigParserusesaninstanceof BasicInterpolation.Thelibraryalsoprovidesa``zc.buildbot`` inspiredExtendedInterpolationimplementation. When`converters`isgiven,itshouldbeadictionarywhereeachkey representsthenameofatypeconverterandeachvalueisacallable implementingtheconversionfromstringtothedesireddatatype.Every convertergetsitscorrespondingget*()methodontheparserobjectand sectionproxies. sections() Returnalltheconfigurationsectionnames,sansDEFAULT. has_section(section) Returnwhetherthegivensectionexists. has_option(section,option) Returnwhetherthegivenoptionexistsinthegivensection. options(section) Returnlistofconfigurationoptionsforthenamedsection. read(filenames,encoding=None) Readandparsetheiterableofnamedconfigurationfiles,givenby name.Asinglefilenameisalsoallowed.Non-existingfiles areignored.Returnlistofsuccessfullyreadfiles. read_file(f,filename=None) Readandparseoneconfigurationfile,givenasafileobject. Thefilenamedefaultstof.name;itisonlyusedinerror messages(iffhasno`name'attribute,thestring`??>'isused). read_string(string) Readconfigurationfromagivenstring. read_dict(dictionary) Readconfigurationfromadictionary.Keysaresectionnames, valuesaredictionarieswithkeysandvaluesthatshouldbepresent inthesection.Iftheuseddictionarytypepreservesorder,sections andtheirkeyswillbeaddedinorder.Valuesareautomatically convertedtostrings. get(section,option,raw=False,vars=None,fallback=_UNSET) Returnastringvalueforthenamedoption.All%interpolationsare expandedinthereturnvalues,basedonthedefaultspassedintothe constructorandtheDEFAULTsection.Additionalsubstitutionsmaybe providedusingthe`vars'argument,whichmustbeadictionarywhose contentsoverrideanypre-existingdefaults.If`option'isakeyin `vars',thevaluefrom`vars'isused. getint(section,options,raw=False,vars=None,fallback=_UNSET) Likeget(),butconvertvaluetoaninteger. getfloat(section,options,raw=False,vars=None,fallback=_UNSET) Likeget(),butconvertvaluetoafloat. getboolean(section,options,raw=False,vars=None,fallback=_UNSET) Likeget(),butconvertvaluetoaboolean(currentlycase insensitivelydefinedas0,false,no,offforFalse,and1,true, yes,onforTrue).ReturnsFalseorTrue. items(section=_UNSET,raw=False,vars=None) Ifsectionisgiven,returnalistoftupleswith(name,value)for eachoptioninthesection.Otherwise,returnalistoftupleswith (section_name,section_proxy)foreachsection,includingDEFAULTSECT. remove_section(section) Removethegivenfilesectionandallitsoptions. remove_option(section,option) Removethegivenoptionfromthegivensection. set(section,option,value) Setthegivenoption. write(fp,space_around_delimiters=True) Writetheconfigurationstatein.iniformat.If `space_around_delimiters'isTrue(thedefault),delimiters betweenkeysandvaluesaresurroundedbyspaces.
配置文件的数据格式
下面的config.ini展示了配置文件的数据格式,用中括号[]括起来的为一个section例如Default、Color;每一个section有多个option,例如serveraliveinterval、compression等。
option就是我们用来保存自己数据的地方,类似于键值对optionname=value或者是optionname:value(也可以设置允许空值)
[Default] serveraliveinterval=45 compression=yes compressionlevel=9 forwardx11=yes valueslikethis:1000000 orthis:3.14159265359 [NoValues] key_without_value emptystringvaluehere= [Color] isset=true version=1.1.0 orange=150,100,100 lightgreen=0,220,0
数据类型
在pyconfigparser保存的数据中,value的值都保存为字符串类型,需要自己转换为自己需要的数据类型
Configparsersdonotguessdatatypesofvaluesinconfigurationfiles,alwaysstoringtheminternallyasstrings.Thismeansthatifyouneedotherdatatypes,youshouldconvertonyourown:
例如
>>>int(topsecret['Port']) 50022 >>>float(topsecret['CompressionLevel']) 9.0
常用方法method
打开配置文件
importconfigparser file='config.ini' #创建配置文件对象 cfg=configparser.ConfigParser(comment_prefixes='#') #读取配置文件 cfg.read(file,encoding='utf-8')
这里只打开不做什么读取和改变
读取配置文件的所有section
file处替换为对应的配置文件即可
importconfigparser file='config.ini' cfg=configparser.ConfigParser(comment_prefixes='#') cfg.read(file,encoding='utf-8') #获取所有section sections=cfg.sections() #显示读取的section结果 print(sections)
判断有没有对应的section!!!
当没有对应的section就直接操作时程序会非正常结束
importconfigparser file='config.ini' cfg=configparser.ConfigParser(comment_prefixes='#') cfg.read(file,encoding='utf-8') ifcfg.has_section("Default"):#有没有"Default"section print("存在Defaulsection") else: print("不存在Defaulsection")
判断section下对应的Option
importconfigparser file='config.ini' cfg=configparser.ConfigParser(comment_prefixes='#') cfg.read(file,encoding='utf-8') #检测Defaultsection下有没有"CompressionLevel"option ifcfg.cfg.has_option('Default','CompressionLevel'): print("存在CompressionLeveloption") else: print("不存在CompressionLeveloption")
添加section和option
最最重要的事情:最后一定要写入文件保存!!!不然程序修改的结果不会修改到文件里
- 添加section前要检测是否存在,否则存在重名的话就会报错程序非正常结束
- 添加option前要确定section存在,否则同1
option在修改时不存在该option就会创建该option
importconfigparser file='config.ini' cfg=configparser.ConfigParser(comment_prefixes='#') cfg.read(file,encoding='utf-8') ifnotcfg.has_section("Color"):#不存在Colorsection就创建 cfg.add_section('Color') #设置sectin下的option的value,如果section不存在就会报错 cfg.set('Color','isset','true') cfg.set('Color','version','1.1.0') cfg.set('Color','orange','150,100,100') #把所作的修改写入配置文件 withopen(file,'w',encoding='utf-8')asconfigfile: cfg.write(configfile)
删除option
importconfigparser file='config.ini' cfg=configparser.ConfigParser(comment_prefixes='#') cfg.read(file,encoding='utf-8') cfg.remove_option('Default','CompressionLevel' #把所作的修改写入配置文件 withopen(file,'w',encoding='utf-8')asconfigfile: cfg.write(configfile)
删除section
删除section的时候会递归自动删除该section下面的所有option,慎重使用
importconfigparser file='config.ini' cfg=configparser.ConfigParser(comment_prefixes='#') cfg.read(file,encoding='utf-8') cfg.remove_section('Default') #把所作的修改写入配置文件 withopen(file,'w',encoding='utf-8')asconfigfile: cfg.write(configfile)
实例
创建一个配置文件
importconfigparser file='config.ini' #创建配置文件对象 cfg=configparser.ConfigParser(comment_prefixes='#') #读取配置文件 cfg.read(file,encoding='utf-8')``` #实例 ##创建一个配置文件 下面的demo介绍了如何检测添加section和设置value ```python #!/usr/bin/envpython #-*-encoding:utf-8-*- ''' @File:file.py @Desc:使用configparser读写配置文件demo @Author:Kearney @Contact:191615342@qq.com @Version:0.0.0 @License:GPL-3.0 @Time:2020/10/2010:23:52 ''' importconfigparser file='config.ini' #创建配置文件对象 cfg=configparser.ConfigParser(comment_prefixes='#') #读取配置文件 cfg.read(file,encoding='utf-8') ifnotcfg.has_section("Default"):#有没有"Default"section cfg.add_section("Default")#没有就创建 #设置"Default"section下的option的value #如果这个section不存在就会报错,所以上面要检测和创建 cfg.set('Default','ServerAliveInterval','45') cfg.set('Default','Compression','yes') cfg.set('Default','CompressionLevel','9') cfg.set('Default','ForwardX11','yes') ifnotcfg.has_section("Color"):#不存在Color就创建 cfg.add_section('Color') #设置sectin下的option的value,如果section不存在就会报错 cfg.set('Color','isset','true') cfg.set('Color','version','1.1.0') cfg.set('Color','orange','150,100,100') cfg.set('Color','lightgreen','0,220,0') ifnotcfg.has_section("User"): cfg.add_section('User') cfg.set('User','iscrypted','false') cfg.set('User','Kearney','191615342@qq.com') cfg.set('User','Tony','backmountain@gmail.com') #把所作的修改写入配置文件,并不是完全覆盖文件 withopen(file,'w',encoding='utf-8')asconfigfile: cfg.write(configfile)
跑上面的程序就会创建一个config.ini的配置文件,然后添加section和option-value
文件内容如下所示
[Default] serveraliveinterval=45 compression=yes compressionlevel=9 forwardx11=yes [Color] isset=true version=1.1.0 orange=150,100,100 lightgreen=0,220,0 [User] iscrypted=false kearney=191615342@qq.com tony=backmountain@gmail.com
References
Configurationfileparser-py2
Configurationfileparser-py3
python读取配置文件(ini、yaml、xml)-ini只读不写。。
python编写配置文件-open不规范,注释和上一篇参考冲突
到此这篇关于详解Python利用configparser对配置文件进行读写操作的文章就介绍到这了,更多相关Pythonconfigparser配置文件读写内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!