用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser
一.生成一个configpaser文档
#!/usr/bin/env python
#coding=utf-8
__author__ = ‘yaobin‘
#生成一个configparse文档
import configparser
config = 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 parser
topsecret[‘ForwardX11‘] = ‘no‘ # same here
config[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘
with open(‘example.ini‘, ‘w‘) as configfile:
config.write(configfile)
二.读增删改
#!/usr/bin/env python
#coding=utf-8
__author__ = ‘yaobin‘
import configparser
config = 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"))
时间: 2024-12-19 15:06:14