码迷,mamicode.com
首页 > 其他好文 > 详细

标准库模块:ConfigParse

时间:2018-05-10 21:38:57      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:forward   .section   技术   with open   sam   python   with   标准   span   

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

常见文档格式

技术分享图片
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no
conf

文档生成

import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,
                     ‘Compression‘: ‘yes‘,
                     ‘CompressionLevel‘: ‘9‘}

config[‘bitbucket.org‘] = {}
config[‘bitbucket.org‘][‘User‘] = ‘hg‘
config[‘topsecret.server.com‘] = {}
topsecret = config[‘topsecret.server.com‘]
topsecret[‘Host Port‘] = ‘50022‘  # mutates the parser
topsecret[‘ForwardX11‘] = ‘no‘  # same here
config[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘
with open(‘example.ini‘, ‘w‘) as configfile:
  config.write(configfile)

  文档读、改、删

import configparser
config = configparser.ConfigParser()

config.read(‘example.ini‘)

print(config.sections())  #只打印节点
#增
print(config[‘bitbucket.org‘][‘user‘])
#改
sec=config.remove_section(‘bitbucket.org‘)
config.write(open(‘example.cfg‘,‘w‘))

 

标准库模块:ConfigParse

标签:forward   .section   技术   with open   sam   python   with   标准   span   

原文地址:https://www.cnblogs.com/q1ang/p/9021664.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!