python cfg文件操作

佐手、 提交于 2019-12-02 15:44:34

格式:

[section]
option = value

 

 

import ConfigParser

config=ConfigParser.ConfigParser()

#读
config.read('test.cfg')
#with open('test.cfg','r') as f:
#  config.readfp(f,'test.cfg')

print config.sections() #获取所有的section
print config.has_section(section) #判断是否有section
print config.has_option(section,option) #判断是否有option
print config.options(section) #获取section里面的所有的option
print config.items(section) #获取section里面的所有的(option,value)键值对
print config.get(section,option) #获取value

#写
config.add_section('section') #添加一个section
config.set('section1','name','aaa') #添加section的option,value
with open('test.cfg','a+') as f:
  config.write(f) #写入文件


#删除
config.read('test.cfg')
config.remove_section('section')
config.remove_option('section','option')
with open('test.cfg','w') as f:
  config.write(f)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!