This article example describes how Python uses the ConfigParser module to manipulate configuration files. Shared for your reference, as follows:
I. Introduction
Used to generate and modify common configuration documents, the name of the current module has changed in the python version toconfigparser
。
II. Configuration file format
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [] User = hg [] Port = 50022 ForwardX11 = no
III. Creating configuration files
import configparser # Generate a processing object config = () # Default Configuration config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'} # Generate additional configuration groups config[''] = {} config['']['User'] = 'hg' config[''] = {} topsecret = config[''] topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] = 'no' # same here config['DEFAULT']['ForwardX11'] = 'yes' # Write to configuration file with open('', 'w') as configfile: (configfile)
IV. Reading configuration files
1、Read node information
import configparser config = () ('') # Read default configuration node information print(()) #Read other nodes print(())
exports
OrderedDict([('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
['', '']
2. Read whether the configuration node name exists
print('ssss' in config) print('' in config)
exports
False
True
3、Read the information inside the configuration node
print(config['']['user'])
exports
hg
4. Loop to read all the information of the configuration node
for key in config['']: print(key, ':', config[''][key])
exports
user : hg
compression : yes
serveraliveinterval : 45
compressionlevel : 9
forwardx11 : yes
Readers interested in more Python related content can check out this site's topic: theSummary of Python function usage tips》、《Python Object-Oriented Programming Introductory and Advanced Tutorials》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques》
I hope that what I have said in this article will help you in Python programming.