lightconfig是一个简单的库,可以让用户读取或写入配置
lightconfig的Python项目详细描述
lightconfig库使您能够轻松地创建或读取配置文件
安装
lightconfig可以通过pip方便地使用:
pip install lightconfig
或通过git clone和setup.py安装
git clone https://github.com/daassh/LightConfig.git python setup.py install
用法
导入
fromlightconfigimportLightConfig
创建
cfg=LightConfig("config.ini")
< CIT>(如果特定路径不存在,将创建路径文件)
读/写
通常,您可以按属性和项读取/写入配置
按属性读/写
>>>cfg.section.option='value'>>>cfg.section.option'value'
按项目读/写
>>>cfg['section']['option']='value'>>>cfg['section']['option']'value'
按节编写
>>>cfg.section1={'option1':'value1'}>>>cfg['section2']={'option2':'value2'}>>>cfg{'section1':{'option1':'value1'},'section2':{'option2':'value2'}}
但在某些情况下,只能使用按项读/写
节/选项名不能是python变量名
错误
>>>cfg.section-2.2option='value2'...SyntaxError:invalidsyntax
右
>>>cfg['section-2']['2option']='value2'
节/选项名称是键或命令
键和dict是lightconfig的内部方法(键用于使lightconfig对象可写,dict用于访问lightconfig的其他内部方法),因此当使用键或dict作为节/选项名称时,您只能按项目访问它:
错误
>>>cfg.keys.option3='value3'...AttributeError:'method'objecthasnoattribute'option3>>>cfg.keys<boundmethodLightConfig.keysof...>>>>cfg.__dict__.option4='value4'...AttributeError:'dict'objecthasnoattribute'option4'>>>cfg.__dict__{'_config_path':'','_try_encoding':{},...}
右
>>>cfg['keys'].option3='value3'>>>cfg['keys']{'option3':'value3'}>>>cfg['__dict__'].option4='value4'>>>cfg['__dict__']{'option4':'value4'}
删除
使用del删除节/选项:
>>>delcfg.section.option>>>'option'incfg.sectionFalse>>>delcfg['section']>>>'section'incfgFalse
可听写
使用dict将lightconfig或lightconfig.section对象转换为dict:
>>>type(dict(cfg))<class'dict'>>>>type(dict(cfg.section))<class'dict'>
Iterable
>>>forsection_name,section_infoincfg:...print(section_name)...foroption,valueinsection_info:...print(' {}={}'.format(option,value))section1option1=value1section2option2=value2