首页 > 其他 > 详细

022configparser模块

时间:2018-01-01 10:09:09      阅读:198      评论:0      收藏:0      [点我收藏+]


#配置模块

#创建
import  configparser

config  =  configparser.ConfigParser()

#添加
config["DEFAULT"]  =  {‘ServerAliveInterval‘:‘45‘,
    ‘Compression‘:‘yes‘,
    ‘CompressionLevel‘:‘9‘}

config[‘bitbucket.org‘] = {‘User‘:‘hg‘}
#config[‘bitbucket.org‘]={}
#config[‘bitbucket.org‘][‘User‘]=‘hg‘
config[‘topsecret.server.com‘] = {}
topsecret = config[‘topsecret.server.com‘]
topsecret[‘HostPort‘] = ‘50022‘#mutatestheparser
topsecret[‘ForwardX11‘] = ‘no‘#samehere
config[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘

#通过下面这个写入到文件
with  open(‘example.ini‘,‘w‘) as  configfile:
    config.write(configfile)

#读取
config.read(‘example.ini‘)
print(config.sections())                    #  [‘bitbucket.org‘,‘topsecret.server.com‘]
print(config.default_section)      #  DEFAULT
print(config.defaults())#OrderedDict([(‘serveraliveinterval‘,‘45‘),(‘compression‘,‘yes‘),(‘compressionlevel‘,‘9‘),(‘forwardx11‘,‘yes‘)])

print(config[‘bitbucket.org‘][‘User‘])     #  hg

for  key  in  config[‘bitbucket.org‘]:         # 和for key in config: 有区别
    print(key)
#user
#serveraliveinterval
#compression
#compressionlevel
#forwardx11

# 删除
config.remove_section(‘topsecret.server.com‘)   # 没有办法改原来的文件
config.write(open(‘i.cfg‘,‘w‘))     # 重新生成一个文件
config.remove_option(‘bitbucket.org‘,‘user‘)

# 判断是否存在
print(config.has_section(‘topsecret.server.com‘))

#更改
config.set(‘bitbucket.org‘,‘user‘,‘aiq‘)
config.write(open(‘example.ini‘,‘w‘))

###凡是更改了里面的内容都需要重新写入

022configparser模块

原文:https://www.cnblogs.com/-nbloser/p/8160223.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!