18-3 常用模块(configparser)

来看一个好多软件的常见文档格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

 

1. 创建配置文件

import configparser

config = configparser.ConfigParser()               # 新建一个配置文件句柄
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'                   # 当然也可以这样写
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'


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

 

2. 查

import configparser

config = configparser.ConfigParser()


print(config.sections())     # [] 因为此时config尚未读入内容
config.read('example.ini')
print(config.sections())     # ['bitbucket.org', 'topsecret.server.com']  注意:DEFAULT不写入此列表中
print(config.defaults())     # OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
print('bytebong.com' in config)                       # False
print(config['bitbucket.org']['User'])                # hg
print(config['DEFAULT']['Compression'])               # yes
print(config['topsecret.server.com']['ForwardX11'])   # no

for key in config['topsecret.server.com']:
    print(key)            # 同时也会打印出DEFAULT的key

# 结果:
# host port
# forwardx11              # forwardx11 在 DEFAULT和 ['topsecret.server.com']中都有,去重输出一个
# serveraliveinterval
# compression
# compressionlevel


print(config.options('bitbucket.org'))  # ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
print(config.items('bitbucket.org'))    # [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
print(config.get('bitbucket.org','compression'))   # yes

 

3. 增、删、改

import configparser

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


config.add_section('yuan')           # 增加新的section
config.set('yuan', 'k1', '22222')    # 往新section中加入option。对于已经存在的option,此命令可对其进行修改。

config.remove_section('topsecret.server.com')     # 删除section
config.remove_option('bitbucket.org','user')      # 删除option


config.write(open('i.cfg', "w"))     # 所有的增删改操作,最后都必须有这句。如果文件名写成example.ini,是将原example.ini覆盖
posted @ 2017-06-22 08:15  seaidler  阅读(106)  评论(0)    收藏  举报