Python configparser模块

configparser模块

 

 

一.configparser模块

用于生成和修改常见配置文档,但那个钱模块名称在python3.x版本中变更为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'

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

config.write(configfile)

注:生成配置文件example.ini

 

2.读取配置文件

import configparser

conf = configparser.ConfigParser()

conf.read("example.ini")

print(conf.defaults())

print(conf.sections())

print(conf['bitbucket.org']['user'])


注:conf.defaults:读取的是defaults以字典类型读取

注:conf.sections:读取的是节点,不包含defaults。

注:conf['bitbucket.org']['user']:则是直接读取节点下内容。

 

4.删除配置文件内容。

import configparser

conf = configparser.ConfigParser()

conf.read("example.ini")

print(conf.defaults())

print(conf.sections())

print(conf['bitbucket.org']['user'])

sec = conf.remove_section('bitbucket.org')

conf.write(open('exmple2.cfg',"w"))

注:删除并创建备份新的文件内。

posted @ 2017-11-05 12:47  kevin.Xiang  阅读(1788)  评论(0编辑  收藏  举报