python configparser模块

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', '11111')
# 删除模块
config.remove_section('topsecret.server.com')
# 删除键值
config.remove_option('bitbucket.org', 'user')
# 重新写入配置
config.write(open('i.cfg', "w"))

 

posted @ 2019-09-06 14:27  The_small_white  阅读(219)  评论(0编辑  收藏  举报