In practical applications, the Python programming language idea helps us create many useful values. It is a simple object-oriented programming language, which contains many useful modules for us to use. Today, we will introduce the application of one of the most important Python ConfigParser modules.
It is common to use a configuration file in a program to flexibly configure some parameters. The parsing of configuration files is not complicated, especially in Python, the officially released library contains the library for doing this, that is, ConfigParser. Here is a brief introduction.
The format of the configuration file parsed by the Python ConfigParser module is similar to that of the ini configuration file, which consists of multiple sections. Each section has multiple configuration items, such:
- [db]
- db_host=127.0.0.1
- db_port=3306
- db_user=root
- db_pass=password
- [concurrent]
- thread=10
- processor=20
Assume that the configuration file above is named test. conf. It contains two sections, one is db, the other is concurrent, the db also contains four items, and the concurrent contains two items. Here we will do the parsing:
- #-*-Encoding: gb2312 -*-
- Import ConfigParser
- Import string, OS, sys
- Cf = ConfigParser. ConfigParser ()
- Cf. read ("test. conf ")
- # Return all sections
- S = cf. sections ()
- Print 'section: ', s
- O = cf. options ("db ")
- Print 'Options: ', o
- V = cf. items ("db ")
- Print 'db: ', v
- Print '-' * 60
- # Read data by type
- Db_host = cf. get ("db", "db_host ")
- Db_port = cf. getint ("db", "db_port ")
- Db_user = cf. get ("db", "db_user ")
- Db_pass = cf. get ("db", "db_pass ")
- # The returned result is an integer.
- Threads = cf. getint ("concurrent", "thread ")
- Processors = cf. getint ("concurrent", "processor ")
- Print "db_host:", db_host
- Print "db_port:", db_port
- Print "db_user:", db_user
- Print "db_pass:", db_pass
- Print "thread:", threads
- Print "processor:", processors
- # Modify a value and write it back.
- Cf. set ("db", "db_pass", "zhaowei ")
- Cf. write (open ("test. conf", "w "))
The preceding section describes the application methods of the Python ConfigParser module.