python configparser模块
发布时间:2020-12-20 10:47:52 所属栏目:Python 来源:网络整理
导读:import configparser # 创建配置文件 config = configparser.ConfigParser() # config={} # config[ " DEFAULT " ] = { ‘ ServerAliveInterval ‘ : ‘ 45 ‘ , ‘ Compression ‘ : ‘ yes ‘ , ‘ CompressionLevel ‘ : ‘ 9 ‘ }config[ ‘ bitbucket.o
import configparser # 创建配置文件 config = configparser.ConfigParser() # config={} # 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 with open(‘example.ini‘,‘w‘) as f: config.write(f) # 对配置文件进行操作 # 读取配置文件 config.read(‘example.ini‘) # 读取配置文件模块 ,DEFAULT模块不显示 ret = config.sections() print(ret) # [‘bitbucket.org‘,‘topsecret.server.com‘] print(‘bytebong.com‘ in config) # False # 读取模块下的键值 print(config[‘bitbucket.org‘][‘User‘]) # hg 读取模块下的键值 print(config[‘DEFAULT‘][‘Compression‘]) # yes print(config[‘topsecret.server.com‘][‘ForwardX11‘]) # no # 在 DEFAULT模块下的键值,其他模块都能获取 for key in config[‘bitbucket.org‘]: print(key) # 结果 # user # serveraliveinterval # compression # compressionlevel # options 获取模块下的所有键名,存入列表,包括DEFAULT模块下的键名 ret = config.options(‘bitbucket.org‘) print(ret) # [‘user‘,‘serveraliveinterval‘,‘compression‘,‘compressionlevel‘] # items 获取模块下的所有键值,以元组形式存入列表,包括DEFAULT模块下的键名 ret = config.items(‘bitbucket.org‘) print(ret) # [(‘serveraliveinterval‘,‘45‘),(‘compression‘,‘yes‘),(‘compressionlevel‘,‘9‘),(‘user‘,‘hg‘)] # 获取指定模块下的值 ret = config.get(‘bitbucket.org‘,‘compression‘) print(ret) # yes # 新增模块 config.add_section(‘yuan‘) # 新增键值 config.set(‘yuan‘,‘k1‘,‘22222‘) # 删除模块 config.remove_section(‘topsecret.server.com‘) # 删除键值 config.remove_option(‘bitbucket.org‘,‘user‘) # 重新写入配置 config.write(open(‘i.cfg‘,"w")) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |