Python ConfigParser 模块

用于生成和修改常见配置文档

import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',   # 方法一:增加一个 default setion
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['klvchen.com'] = {}                          # 方法二:增加一个 klvchen.com setion
config['klvchen.com']['User'] = 'kl'

config['topsecret.server.com'] = {}                 # 方法三:添加一个 topsecret.server.com
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'     
topsecret['ForwardX11'] = 'no'  

with open('example.ini', 'w') as configfile:
   config.write(configfile)

在当前目录下生成 example.ini 文档:

[DEFAULT]
compressionlevel = 9
compression = yes
serveraliveinterval = 45

[klvchen.com]
user = kl

[topsecret.server.com]
host port = 50022
forwardx11 = no

常见的操作

import configparser
config = configparser.ConfigParser()
config.read('example.ini')

# 获取 DEFAULT 的键值
print(config.defaults())
运行结果:
OrderedDict([('compressionlevel', '9'), ('compression', 'yes'), ('serveraliveinterval', '45')])


# 获取除 DEFAULT 外的 setion
print(config.sections()) 
运行结果: ['bitbucket.org', 'topsecret.server.com']


# 判断 setion 是否存在
print('klvchen.com' in config)
运行结果: True

print(config.has_section('klvchen.com'))
运行结果: True


# 获取 setion 中的某个键值
print(config['klvchen.com']['User'])
运行结果: kl

print(config['DEFAULT']['compression'])
运行结果: yes


# 获取所有的 setion,包括 default
for key in config:
    print(key)
运行结果:
DEFAULT
klvchen.com
topsecret.server.com


# 删除setion
config.remove_section('topsecret.server.com')  # 整个setion下的键值对都会删除
config.write(open('example.ini', 'w'))         # 需要重新写入文件


# klvchen.com setion 下修改键值,没有即添加 
config.set('klvchen.com', 'age', '28')
config.write(open('example.ini', 'w'))         # 需要重新写入文件

猜你喜欢

转载自www.cnblogs.com/klvchen/p/8881504.html
今日推荐