Detailed explanation of the usage of configparser module parsing configuration in Python3

Introduction to configparser

configparser is a module in the Pyhton standard library for parsing configuration files, and the built-in methods are very close to dictionaries. Named ConfigParser in Python 2.x, 3.x has been renamed to lowercase and some new features have been added.
The format of the configuration file is as follows:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = Tom [topsecret.com] Port: 50022 ForwardX11: no

"[ ]" contains section, and the following section contains configuration content similar to key-value;
configparser supports '=' ':' by default.


configparser common methods

Initialize the instance

To use configparser, you first need to initialize the instance and read the configuration file:

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

Or you can read the dictionary directly

>>> parser = configparser.ConfigParser()
>>> parser.read_dict({'section1': {'key1': 'value1',
...                                'key2': 'value2', ... 'key3': 'value3'}, ... 'section2': {'keyA': 'valueA', ... 'keyB': 'valueB', ... 'keyC': 'valueC'}, ... 'section3': {'foo': 'x', ... 'bar': 'y', ... 'baz': 'z'} ... })

get all sections

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

Get the keys & values ​​of the specified section

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

Get the keys of the specified section

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

Get the value of the specified key

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

an examination

>>> '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

Add to

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

delete

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

About [DEFAULT]

[DEFAULT] Generally contains default items in ini format configuration files, so some methods of configparser will automatically skip this section.
As mentioned earlier, sections() cannot be obtained, and the delete method is also invalid for [DEFAULT]:

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

But it is possible to specify deletion and modification of keys & values ​​in [DEFAULT]:

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

Another special thing is that has_section() is also invalid and can be used differently from in

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325970543&siteId=291194637