类字典操作,不区分大小写
DEFAULT默认块在遍历其他块时也会被遍历
创建配置文件
#!/usr/bin/env python
import configparser
config = configparser.ConfigParser() #config={}
config['DEFAULT']={ #创建默认块
'Serveraliveinterval':45,
'compressionlevel':9,
'compression':'yes'
}
config['topsecret.server.com'] = {} #创建块
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022' #给块添加元素
with open('example.ini','w') as configfile:
config.write(configfile) #与一般文件写入格式不同,是调用的实例的write方法
结果:
创建文件example.ini
内容:
[DEFAULT]
serveraliveinterval = 45
compressionlevel = 9
compression = yes
[topsecret.server.com]
host port = 50022
config.sections()查询块
#!/usr/bin/env python
import configparser
config = configparser.ConfigParser() #config={}
config.read('example.ini') #读取配置文件,括号里加路径
print(config.sections()) #取块,除了默认块
print(config['topsecret.server.com']['host port']) #取出块里键对应的值
输出:
[‘topsecret.server.com’]
50022
config.options()取块里的键,放入列表,包括默认块里的键
#!/usr/bin/env python
import configparser
config = configparser.ConfigParser() #config={}
config.read('example.ini') #读取配置文件
print(config.options('topsecret.server.com'))
输出:
[‘host port’, ‘serveraliveinterval’, ‘compressionlevel’, ‘compression’]
config.items()取块里的键值对,放入列表,包括默认块里的键值对
#!/usr/bin/env python
import configparser
config = configparser.ConfigParser() #config={}
config.read('example.ini') #读取配置文件
print(config.items('topsecret.server.com'))
输出:
[(‘serveraliveinterval’, ‘45’), (‘compressionlevel’, ‘9’), (‘compression’, ‘yes’), (‘host port’, ‘50022’)]
config.get()取块里的键对应的值
#!/usr/bin/env python
import configparser
config = configparser.ConfigParser() #config={}
config.read('example.ini') #读取配置文件
print(config.get('topsecret.server.com','host port'))
改值,改后写入文件
#!/usr/bin/env python
import configparser
config = configparser.ConfigParser() #config={}
config.read('example.ini') #读取配置文件
config['topsecret.server.com']['host port'] = '111' #改对应的值
config.write(open('example.ini','w')) #写入文件
增加块config.add_section()和增加键值对config.set()
#!/usr/bin/env python
import configparser
config = configparser.ConfigParser() #config={}
config.read('example.ini') #读取配置文件
config.add_section('malin') #增块
config.set('malin','k1','111') #增加键值对
config.write(open('example.ini','w'))
文件内容:
[DEFAULT]
serveraliveinterval = 45
compressionlevel = 9
compression = yes
[topsecret.server.com]
host port = 111
[malin]
k1 = 111
删除块 config.remove_section()
删除块里的键值对config.remove_option()
#!/usr/bin/env python
import configparser
config = configparser.ConfigParser() #config={}
config.read('example.ini') #读取配置文件
config.remove_option('topsecret.server.com','host port') #删除块里的键值对
config.remove_section('malin') #删除块
config.write(open('example.ini','w'))