ConfigParser模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

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

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

python生成配置文件

import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '',
'Compression': 'yes',
'CompressionLevel': ''} config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)

读取配置文件信息

#!/usr/bin/env python3
# -*- coding:utf-8 -*- import configparser config = configparser.ConfigParser()
config.sections() config.read('example') config.sections() for i in config.keys():
print(i, end=' ')
print("=" * 50)
print(config.keys()) print(config['bitbucket.org']['User']) print(config['DEFAULT']['Compression']) topsecret = config['topsecret.server.com']
print(topsecret['ForwardX11'])
print(topsecret['Port']) for key in config['bitbucket.org']:
print(key) print(config['bitbucket.org']['ForwardX11'])

configparser增删改查语法

 
########### i.cfg file ##########
[section1]
k1 = v1
k2:v2
k5 : 10 [section2]
k3 = v3
k4 = v4
age : 88
#################################
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: songwei import configparser # ########## 读 ########## config = configparser.ConfigParser()
config.read('example') secs = config.sections()
print(secs) #--->['section1', 'section2']
options = config.options('section2')
print(options) #--->['k3', 'k4', 'age'] item_list = config.items('section2')
print(item_list) #--->[('k3', 'v3'), ('k4', 'v4'), , ('age', '88')] val = config.get("section1", "k2")
print(val) #--->v2
val2 = config.getint('section1','k5')
print(val2) #---> 10 # ########## 改写 ########## config = configparser.ConfigParser()
config.read('example')
sec = config.remove_section('section1') #删除
config.write(open('i.cfg', "w")) sec = config.has_section('wupeiqi')
print(sec)
sec = config.add_section('wupeiqi')
print(sec)
config.write(open('i.cfg', "w")) config.set('section2','k4',"")
# config.defaults()
config.write(open('i.cfg', "w")) # config.remove_option('section2','age')
# config.write(open('i.cfg', "w"))
05-11 05:05