python的ConfigParser模块

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

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

 1 [DEFAULT]
 2 ServerAliveInterval = 45
 3 Compression = yes
 4 CompressionLevel = 9
 5 ForwardX11 = yes
 6 
 7 [bitbucket.org]
 8 User = Tom
 9 
10 [topsecret.com]
11 Port: 50022
12 ForwardX11: no

configparser 常用方法

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

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

2.获取所有 sections

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

3.获取指定 section 的 keys & values

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

4.获取指定 section 的 keys

1 >>> config.options('topsecret.com')
2 ['Port', 'ForwardX11']
3 
4 >>> for option in config['topsecret.com']:
5 ...     print(option)
6 Port
7 ForwardX11

5.获取指定 key 的 value

1 >>> config['bitbucket.org']['User']
2 'Tom'
3 >>> config.get('bitbucket.org', 'User')
4 'Tom'
5 >>> config.getint('topsecret.com', 'Port')
6 50022

6.检查

 1 >>> 'DEFAULT' in config
 2 True
 3 >>> 'test' in config['section_test']
 4 False
 5 >>> 'Tom' in config['bitbucket.org']['User']
 6 True
 7 
 8 >>> config.has_section('bitbucket.org')
 9 True
10 >>> config.has_option('section_test', 'test')
11 False

7.添加

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

8.删除

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

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

1 >>> config.remove_section('DEFAULT')
2 False
3 >>> config.clear()
4 >>> 'DEFAULT' in config
5 True
6 >>> 'ForwardX11' in config['DEFAULT']
7 True
8 >>> config.sections()
9 []

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

1 >>> config.remove_option('DEFAULT', 'ForwardX11')
2 True
3 >>> config.set('DEFAULT', 'ForwardX11','no')
4 >>> config['DEFAULT']['ForwardX11']
5 'no'

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

1 >>> config.has_section('DEFAULT')
2 False
3 >>> 'DEFAULT' in config
4 True
原文地址:https://www.cnblogs.com/cmnz/p/9101574.html