标签:
用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser
#!/usr/bin/env python#coding=utf-8__author__ = ‘yaobin‘#生成一个configparse文档import configparserconfig = configparser.ConfigParser()#生成第一个节段config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,‘Compression‘: ‘yes‘,‘CompressionLevel‘: ‘9‘}#生成第二个节段config[‘bitbucket.org‘] = {}config[‘bitbucket.org‘][‘User‘] = ‘hg‘config[‘bitbucket.org‘][‘passwd‘] = ‘123456‘#生成第三个节段config[‘topsecret.server.com‘] = {}topsecret = config[‘topsecret.server.com‘]topsecret[‘Host Port‘] = ‘50022‘ # mutates the parsertopsecret[‘ForwardX11‘] = ‘no‘ # same hereconfig[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘with open(‘example.ini‘, ‘w‘) as configfile:config.write(configfile)
#!/usr/bin/env python#coding=utf-8__author__ = ‘yaobin‘import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)# ########## 读 ########### secs = config.sections()# print(secs)# options = config.options(‘bitbucket.org‘)# print(options)# item_list = config.items(‘bitbucket.org‘)# print(item_list)# val = config.get(‘bitbucket.org‘,‘user‘)# val2 = config.getint(‘bitbucket.org‘,‘passwd‘)# print(val)# print(val2)# a="bitbucket.org" in config# print(a)## b="bitbucket.orgno" in config# print(b)# d=config[‘bitbucket.org‘][‘User‘]# e=config[‘DEFAULT‘][‘Compression‘]# print(d)# print(e)# topsercret=config[‘topsecret.server.com‘]# print(topsercret[‘forwardx11‘])# print(topsercret[‘host port‘])# for key in config[‘bitbucket.org‘]:# print(key) #DEFAULT也打印出来了,DEFAULT是全局变量吧#print(config[‘bitbucket.org‘][‘ForwardX11‘]) #打印默认的出来了# ########## 改写 ########### sec = config.remove_section(‘bitbucket.org‘)# config.write(open(‘a.cfg‘, "w"))# sec = config.has_section(‘bitbucket.org‘)# print(sec)# config.add_section(‘yaobin‘)# config.write(open(‘b.cfg‘, "w"))## config.set(‘yaobin‘,‘k1‘,"11111")# config.write(open(‘c.cfg‘, "w"))## config.remove_option(‘bitbucket.org‘,‘passwd‘)# config.write(open(‘d.cfg‘, "w"))
标签:
原文地址:http://www.cnblogs.com/binhy0428/p/5221245.html