python的ConfigParser模块

时间:2023-03-09 16:34:58
python的ConfigParser模块

前言
  处理配置文件做增、删、改、查 操作。

配置文件的格式如下:“[ ]”包含的为 section,section 下面为类似于 key - value 的配置内容; configparser 默认支持 ‘=’ ‘:’ 两种分隔。

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

configparser 常用方法

1.使用 configparser 首先需要初始化实例,并读取配置文件:

 >>> import configparser
>>> config = configparser.ConfigParser() # 注意大小写
>>> config.read("config.ini") # 配置文件的路径
["config.ini"]

2.获取所有 sections

 >>> config.sections()
['bitbucket.org', 'topsecret.com'] # 注意会过滤掉[DEFAULT]

3.获取指定 section 的 keys & values

 >>> config.items('topsecret.com')
>>>> [('port', ''), ('forwardx11', 'no')] # 注意items()返回的字符串会全变成小写

4.获取指定 section 的 keys

 >>> config.options('topsecret.com')
['Port', 'ForwardX11'] >>> for option in config['topsecret.com']:
... print(option)
Port
ForwardX11

5.获取指定 key 的 value

 >>> config['bitbucket.org']['User']
'Tom'
>>> config.get('bitbucket.org', 'User')
'Tom'
>>> config.getint('topsecret.com', 'Port')
50022

6.检查

 >>> 'DEFAULT' in config
True
>>> 'test' in config['section_test']
False
>>> 'Tom' in config['bitbucket.org']['User']
True >>> config.has_section('bitbucket.org')
True
>>> config.has_option('section_test', 'test')
False

7.添加

 >>> config.add_section('Section_1')
>>> config.set('Section_1', 'key_1', 'value_1') # 注意键值是用set()方法
>>> config.write(open('config.ini', 'w')) # 一定要写入才生效

8.删除

 >>> config.remove_option('Section_1', 'key_1')
True
>>> config.remove_section('Section_1')
True
>>> config.clear() # 清空除[DEFAULT]之外所有内容
>>> config.write(open('config.ini', 'w'))

9.关于 [DEFAULT]:一般包含 ini 格式配置文件的默认项,所以 configparser 部分方法会自动跳过这个 section 。
前面已经提到 sections() 是获取不到的,还有删除方法对 [DEFAULT] 也无效:

 >>> config.remove_section('DEFAULT')
False
>>> config.clear()
>>> 'DEFAULT' in config
True
>>> 'ForwardX11' in config['DEFAULT']
True
>>> config.sections()
[]

但指定删除和修改 [DEFAULT] 里的 keys & values 是可以的:

 >>> config.remove_option('DEFAULT', 'ForwardX11')
True
>>> config.set('DEFAULT', 'ForwardX11','no')
>>> config['DEFAULT']['ForwardX11']
'no'

还有个特殊的是,has_section() 也无效,可以和 in 区别使用

 >>> config.has_section('DEFAULT')
False
>>> 'DEFAULT' in config
True