Python (2.7.6) configparser-read-write configuration file

Source: Internet
Author: User

The Configparser module of the Python Standard library provides a set of APIs to read and manipulate configuration files.

Format of the configuration file

A) The configuration file contains one or more sections, each section has its own option;

b) section is denoted by [Sect_name] , where each option is a key-value pair, using delimiter = or : separated;

c) Spaces at the end of the option delimiter are ignored

d) config file using # and; Comments

A simple sample configuration file myapp.conf

# database Source[db]host = 127.0.0.1port = 3306user = Rootpass = root# Ssh[ssh]host = 192.168.1.101user = Hueypass = Huey

Basic operation of Configparser

A) instantiate the Configparser and load the configuration file

CP = Configparser.safeconfigparser () cp.read (' myapp.conf ')

b) Get the section list, option key list, and option key value tuple list

print ' All sections: ', Cp.sections ()        # sections: [' db ', ' ssh ']print ' options of [db]: ', cp.options (' db ')  # option s of [db]: [' host ', ' Port ', ' user ', ' Pass ']print ' items of [ssh]: ', cp.items (' ssh ')    # items of [SSH]: [(' Host ', ' 192.1 68.1.101 '), (' User ', ' Huey '), (' Pass ', ' Huey ')]

c) Read the specified configuration information

print ' host of DB: ', Cp.get (' db ', ' Host ')     # Host of Db:127.0.0.1print ' host of ssh: ', cp.get (' ssh ', ' host ')   # hos T of Ssh:192.168.1.101

d) Read configuration information by type: Getint, GetFloat, and Getboolean

Print type (cp.getint (' db ', ' Port '))        # <type ' int ' >

e) determine if option exists

Print cp.has_option (' db ', ' Host ')    # True

f) Set option

Cp.set (' db ', ' Host ', ' 192.168.1.102 ')

g) Delete option

Cp.remove_option (' db ', ' host ')

h) Determine if a section exists

Print cp.has_section (' db ')    # True

i) Add section

Cp.add_section (' New_sect ')

j) Delete section

Cp.remove_section (' db ')

k) Save configuration, set, Remove_option, Add_section, and remove_section do not modify the configuration file, the Write method can write the configuration of the Configparser object to the file

Cp.write (Open (' myapp.conf ', ' W ')) Cp.write (sys.stdout)
Unicode-encoded configuration

If the configuration file contains Unicode-encoded data, you need to use the codecs module to open the configuration file with the appropriate encoding.

Myapp.conf

[Msg]hello = Hello

config_parser_unicode.py

Import Configparserimport CODECSCP = Configparser.safeconfigparser () with Codecs.open (' myapp.conf ', ' R ', encoding= ' Utf-8 ') as F:    CP.READFP (f) Print cp.get (' msg ', ' hello ')

Allow_no_value

Typically, option is a key-value pair. However, when the Safeconfigparser parameter allow_no_value is set to True, it allows option to not set the value but only as an identity.

Allow_no_value.conf

# option as Flag
[Flag]
Flag_opt

allow_no_value.py

Import CONFIGPARSERCP = Configparser.safeconfigparser (Allow_no_value = True) cp.read (' myapp.conf ') print cp.get (' flag ' , ' flag_opt ');    # None

Allow_no_value is set to False by default, if there is an option in the configuration file that does not have a value set, an exception configparser.parsingerror is thrown when the configuration file is read. When Allow_no_value is set to True, if an option is not set the value, the Has_option method returns the True,get method returns None.

DEFAULT section

If there is a section in the configuration file named DEFAULT, then the other sections extend its option and can override its option.

Db.conf

[default]host = 127.0.0.1port = 3306[db_root]user = Rootpass = Root[db_huey]host = 192.168.1.101user = Hueypass = Huey

default_section.py

Print Cp.get (' Db_root ', ' host ')    # 127.0.0.1print Cp.get (' Db_huey ', ' host ')    # 192.168.1.101

interpolation interpolation

Safeconfigparser provides interpolation features to combine data.

Url.conf

[Default]url =% (protocol) s://% (server) s:% (port) s/[http]protocol = Httpserver = Localhostport = 8080[ftp]url =% ( Protocol) s://% (server) S/protocol = Ftpserver = 192.168.1.102

interpolation_demo.py

Import CONFIGPARSERCP = Configparser.safeconfigparser () cp.read (' url.conf ') print cp.get (' http ', ' URL ')    #// Localhost:8080/print cp.get (' ftp ', ' URL ')     # ftp://192.168.1.102/

For more configparser use, refer to:

http://blog.csdn.net/zm2714/article/details/8002125

Python (2.7.6) configparser-read-write configuration file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.