Python——configparser模块

有很多软件的配置文件都是外置的,比如说这样的软件:

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

这种配置文件和代码互相隔离,互不影响。所以我们可以使用python生成一个这样的配置文件
生成这样的配置文件我们可以使用Python的configparser模块

import configparser

'''生成配置文件'''
config = configparser.ConfigParser()
# 定义存储的键值对字典
config['DEFAULT'] = {'text': 'abc', 'age': 22, 'tuple': (1, 2, 3, 4)}
config['DEFAULT']['ForwardX11'] = 'yes'
config['ANDROID'] = {'number': 139}
android = config['ANDROID']
android['platform'] = '4.4'
android['cpu'] = 'x86'
android['factory'] = 'apple'
config['COMPUTER'] = {}
computer = config['COMPUTER']
computer['type'] = 'notbook'
with open('example.ini', 'w') as file:
    # 使用config写入到文件中
    config.write(file)
'

'''读取配置文件'''
config.read('example.ini')
# 读取default
print(config.defaults()) 
# 读取第一节点
print(config.sections())#>>> ['ANDROID', 'COMPUTER']
# 判断是否存在节点
print('test' in config)
# 读取单个节点的值
print(config['ANDROID']['cpu']) # >>> x86
# 遍历所有
for key in config:
    print(key)
# 得到某个节点下的键
print(config.options('COMPUTER'))
# 获取某个节点下的元素
print(config.items('COMPUTER'))
# 增删改
# 增加
config.read('example.ini')
config.add_section('ADD')
# 删除节点
config.remove_section('COMPUTER')
# 删除节点下的元素
config.remove_option('ANDROID', 'cpu')
# 改
config.set('ANDROID', 'platform', '5.0')

# 操作完毕后写入
config.write(open('example.ini', 'w'))

你可能感兴趣的:(Python——configparser模块)