#_author:star
#date:2019/11/7
# configparser 配置文件模块
import configparser
config=configparser.ConfigParser()
# config['DEFAULT']={'ServerAliveInterval':'45',
# 'Compress':'yes',
# 'CompressionLevel':'9'}
# config['bitbucket.org']={'user':'hg'}
#
# config['topsecret.server.com']={}
# topsecret=config['topsecret.server.com']
# topsecret['Host Part'] ='50022'
#
# with open('example.ini','w') as configfile:
# config.write(configfile)
config.read('example.ini')
print(config.sections())#['bitbucket.org', 'topsecret.server.com'] 除了DEFAULT之外的其他内容
#查看DEFAULT
print(config.defaults())#OrderedDict([('serveraliveinterval', '45'), ('compress', 'yes'), ('compressionlevel', '9')])
print('bitbucket.org' in config)#True print(config['bitbucket.org']['user'])#hg for key in config:
print(key)
# DEFAULT
# bitbucket.org
# topsecret.server.com
print('----------------')
for key1 in config['bitbucket.org']:
print(key1)
# user
# serveraliveinterval
# compress
# compressionlevel
print('-------------')
config.remove_section('topsecret.server.com')#删除某一个块
print(config.has_section('topsecret.server.com'))#False
print(config.has_section('bitbucket.org'))#True config.set('DEFAULT','ServerAliveInterval','66') config.remove_option('DEFAULT','serveraliveinterval')#删除块下的某一个键值对
config.write(open('r.cfg','w'))#无论怎么修改文件,都要最后重写文件,因为文件一旦生成,就无法修改
Output:

configparser 配置文件模块-LMLPHP

configparser 配置文件模块-LMLPHP

05-11 21:48