Python ConfigParser模块

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

文件格式:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

 

生成:

import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',           # 直接生成DEFAULT
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}                                # 生成空的bitbucket.org
config['bitbucket.org']['User'] = 'hg'                      # 再赋值

config['topsecret.server.com'] = {}                         # 生成空的topsecret.server.com
topsecret = config['topsecret.server.com']                  # 再赋值
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here

config['DEFAULT']['ForwardX11'] = 'yes'                     # 给DEFAULT添加新内容
with open('example.ini', 'w') as configfile:                # 打开文件并写入
    config.write(configfile)

 

读取:

import configparser

config = configparser.ConfigParser()

print(config.sections())                        # 开始时为空
config.read('example.ini')                      # 读取文件
print(config.sections())                        # 不打印DEFAULT
print('\n')

print('bitbucket.org' in config)                # 查找bitbucket.org是否存在
print('bytebong.com' in config)
print('\n')

print(config['bitbucket.org']['User'])          # 读取bitbucket.org下的User
print(config['DEFAULT']['Compression'])
print('\n')

topsecret = config['topsecret.server.com']
print(topsecret['ForwardX11'])                  # 读取topsecret.server.com下的ForwardX11
print(topsecret['host port'])
print('\n')

for key in config['bitbucket.org']:             # 读取bitbucket.org下所有的key(包括DEFAULT下的)
    print(key)
print('\n')

print(config['bitbucket.org']['ForwardX11'])    # bitbucket.org下没有ForwardX11,就默认为DEFAULT下的

输出结果:

[]
['bitbucket.org', 'topsecret.server.com']


True
False


hg
yes


no
50022


user
serveraliveinterval
compressionlevel
compression
forwardx11


yes

 

增删改查:

import configparser

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

sec = config.remove_section('bitbucket.org')        # 删除
config.remove_option('topsecret.server.com', 'host port')
config.write(open('new.ini', "w"))

sec = config.has_section('topsecret.server.com')    # 判断是否存在
print(sec)
sec = config.add_section('bytebong.com')            # 添加
config.write(open('new.ini', "w"))


config.set('bytebong.com', 'host port', '1111')     # 修改
config.write(open('new.ini', "w"))

输出结果:

True

posted on 2019-03-24 16:30  doubtful  阅读(1416)  评论(0编辑  收藏  举报

导航