In applications, the configuration file is usually used to define some parameters. For example, the database configuration file is used to record the database string connection, host name, user name, password, and other information. The Windows INI file is a typical configuration file. The INI file consists of multiple blocks, each of which consists of multiple configuration items.
Code [ODBC 32 bit Data Sources]
MS Access Database = Microsoft Access Driver (*. mdb) (32)
Excel Files = Microsoft Excel Driver (*. xls) (32)
DBASE Filrs = Microsoft dBase Driver (*. dbf) (32)
[MS Access Database]
Driver32 = C: \ WINDOWS \ system32 \ odbcjt32.dll
[Excel Files]
Driver32 = C: \ WINDOWS \ system32 \ odbcjt32.dll
[DBASE Files]
Driver32 = C: \ WINDOWS \ system32 \ odbcjt32.dll
Each square bracket represents a configuration block. Multiple Value assignment Expressions Under the configuration block are configuration items.
1. Read the content of the configuration file
The ConfigParser module in the Python standard library is used to parse the configuration file. The ConfigParser class of the ConfigParser module can read the content of the INI file.
Code #! /Usr/bin/env python
# Coding = UTF-8
Import ConfigParser
Config = ConfigParser. ConfigParser ()
Config. read ("odbc. ini ")
Sections = config. sections ()
Print sections
O = config. options ("ODBC 32 bit Data Sources ")
Print o
V = config. items ("ODBC 32 bit Data Sources ")
Print v
Access = config. get ("ODBC 32 bit Data Sources", "Excel Files ")
Print access
2. Write a new configuration item
Config. add_section ("ODBC Driver Count ")
Config. set ("ODBC Driver Count", "count", 2)
F = open ("odbc. ini", "a + ")
Config. write (f)
F. close
3. modify the configuration file
To modify the configuration file, you must first read the INI file, call the set method to set the content of a configuration item under the specified configuration block, and write it to the configuration file.
Code #! /Usr/bin/env python
# Coding = UTF-8
Import ConfigParser
Config = ConfigParser. ConfigParser ()
Config. read ("odbc. ini ")
Config. remove_option ("ODBC Driver Count", "count ")
Config. remove_section ("ODBC Driver Count ")
F = open ("odbc. ini", "w + ")
Config. write (f)
F. close ()