Configparser module application in Python
The Python Configparser module defines 3 classes Rawconfigparser,configparser and Safeconfigparser that operate on INI files. Where Rawcnfigparser is the most basic INI file read class, Configparser, Safeconfigparser supports parsing of the% (value) s variable.
Let's see how to parse an INI file through the Configparser class.
Configuration file Settings.cfg
[DEFAULT]mykey=myvalue [Section_a]key1=value1 key2=value2 key3=value3 [Section_b]key1=value1 key2=value2 key3=value3 [db]db_host=127.0. 0.1 db_port=5432 db_user=Admin db_pass=letmein db_name=Test Db_url = jdbc:postgresql://% (db_host) s:% (db_port) s/% (db_name) s
The test code is as follows
#coding: Utf-8ImportConfigparser, OS# Read configuration fileCP = Configparser.configparser () cp.read ([' Settings.cfg '])# Get all Defaults sectionDefaults = Cp.defaults ()PrintDefaults# Get all sectionsSections = Cp.sections ()PrintSections# Determine if the specified section existshas_db = Cp.has_section (' DB ')Printhas_db# Gets the configuration information for the specified section, only gets the keyOptions = Cp.options (' DB ')PrintOptions# Gets the configuration information for the specified section, gets the key valueItems = Cp.items (' DB ')PrintItems# Gets the configuration information for the specified section and gets the value according to the keyDb_host=cp.get (' DB ',' Db_host ') Db_port=cp.getint (' DB ',' Db_port ') Db_user=cp.get (' DB ',' Db_user ') Db_pass=cp.get (' DB ',' Db_pass ') Db_name=cp.get (' DB ',' db_name ') Db_url=cp.get (' DB ',' Db_url ')PrintDb_host, Db_port, Db_name, Db_user, Db_pass# using the default section valueMyvalue=cp.get (' DB ',' MyKey ')PrintMyValue# Add a sectionCp.add_section (' Section_c ') Cp.set (' Section_c ',' Key1 ',' value111 ') Cp.set (' Section_c ',' Key2 ',' value222 ') Cp.set (' Section_c ',' Key3 ',' value333 ') Cp.set (' Section_c ',' Key4 ',' value444 ') Cp.write (Open ("Test1.cfg","W"))# Remove OptionCp.remove_option (' Section_c ',' Key4 ')# Remove sectionCp.remove_section (' Section_c ') Cp.write (Open ("Test2.cfg","W"))
Please indicate this address in the form of a link.
This address: http://blog.csdn.net/kongxx/article/details/50449163
Configparser module application in Python