Configparser–work with configuration files

Source: Internet
Author: User
Tags configuration settings

Quote: http://pymotw.com/2/ConfigParser/

Use the Configparser module to manage user-editable configuration The files for a application. The configuration files are organized into sections, and each section can contain name-value to pairs for configuration data. Value interpolation using Python formatting strings is also supported, to build values that depend on one another (this I s especially handy for URL and message strings). Configuration File Format

The file format used by Configparser was similar to the format used by older of Microsoft Windows. It consists of one or more named sections, each of the which can contain individual options with names and values.

Config file sections are identified by looking to lines with [and starting with]. The value between the square brackets is the "section name" and can contain any characters except square brackets.

Options are listed one within a section. The line starts with the name of the option, which is separated from the value by a colon (:) or equal sign (=). Whitespace around the separator is ignored when the file is parsed.

A sample configuration file with the section "Bug_tracker" and three options would look like:

[Bug_tracker]
url = http://localhost:8080/bugs/
username = Dhellmann
Password = SECRET
Reading Configuration Files

The most common use for a configuration file was to have a user or system administrator edit the file with a regular text E Ditor to set application behavior defaults, and then have the application read the file, parse it, and act based in its CO Ntents. Use the Read () method of Safeconfigparser to read the configuration file.

From Configparser import safeconfigparser

parser = Safeconfigparser ()
parser.read (' Simple.ini ')

print Parser.get (' bug_tracker ', ' url ')

This program reads the Simple.ini file from the previous section and prints the value of the URL option from the Bug_track Er section.

$ python configparser_read.py

http://localhost:8080/bugs/

The Read () method also accepts a list of filenames. Each name in turn is scanned, and if the file exists it is opened and read.

From Configparser import safeconfigparser
import glob

parser = safeconfigparser ()

candidates = [' Does_not_ Exist.ini ', ' Also-does-not-exist.ini ',
              ' Simple.ini ', ' Multisection.ini ',
              ]

found = Parser.read ( Candidates)

missing = set (candidates)-set (found)

print ' found config files: ', sorted (found)
print ' Missing files     : ', Sorted (Missing)

Read () Returns a list containing the names of the files successfully loaded, so the program can discover which Configurati On the files are missing and decide whether to ignore them.

$ python configparser_read_many.py

Found config files: [' Multisection.ini ', ' Simple.ini ']
Missing files     : [' Also-does-not-exist.ini ', ' Does_not_exist.ini ']
Unicode Configuration Data

Configuration files containing Unicode data should is opened using the codecs module to set the proper encoding value.

Changing the password value of the original input to contain Unicode characters and saving the results in UTF-8 encoding g Ives

[Bug_tracker]
url = http://localhost:8080/bugs/
username = Dhellmann
password =ßéç®é†

The codecs file handle can is passed to READFP () which uses the ReadLine () method of it argument to get lines from the F Ile and parse them.

From Configparser import safeconfigparser
import codecs

parser = Safeconfigparser ()

# Open The file with the C Orrect encoding
with Codecs.open (' Unicode.ini ', ' R ', encoding= ' utf-8 ') as F:
    PARSER.READFP (f)

password = Parser.get (' bug_tracker ', ' password ')

print ' Password: ', Password.encode (' Utf-8 ')
print ' Type    : ', Type (password)
print ' repr ()  : ', repr (password)

The value returned by Get () is a Unicode object, so in, and print it safely it must be re-encoded as UTF-8.

$ python configparser_unicode.py

password:ßéç®é†
Type    : <type ' Unicode ' >
repr ()  : U ' \xdf\ xe9\xe7\xae\xe9\u2020 '
Accessing Configuration Settings

Safeconfigparser includes methods for examining the structure of the parsed configuration, including listing the sections and options, and getting their values. This configuration file includes two sections for separate Web services:

[Bug_tracker]
url = http://localhost:8080/bugs/
username = Dhellmann
password = SECRET

[wiki]
url = http:// localhost:8080/wiki/
username = Dhellmann
Password = SECRET

And this sample program exercies some of the methods for looking at the configuration data, including sections (), Options ( ), and items ().

From Configparser import safeconfigparser

parser = Safeconfigparser ()
parser.read (' Multisection.ini ')

For Section_name in Parser.sections ():
    print ' section: ', section_name
    print '  Options: ', Parser.options ( Section_name)
    for name, value in Parser.items (section_name):
        print '  %s =%s '% (name, value)
    print

Both sections () and options () return lists of strings, while items () returns a list of tuples containing the Name-value PA IRs.

$ python configparser_structure.py

section:bug_tracker
  Options: [' url ', ' username ', ' password ']
  url = http://localhost:8080/bugs/
  username = Dhellmann
  password = SECRET

section:wiki
  Options: [' url ' , ' username ', ' password ']
  url = http://localhost:8080/wiki/
  username = Dhellmann password
  = SECRET
testing whether values are present

To test if a is exists, use Has_section (), passing the section name.

From Configparser import safeconfigparser

parser = Safeconfigparser ()
parser.read (' Multisection.ini ')

For candidate in [' wiki ', ' bug_tracker ', ' Dvcs ']:
    print '%-12s:%s '% (candidate, parser.has_section (candidate))

Testing if a section exists before calling get () avoids to exceptions for missing data.

$ python configparser_has_section.py

wiki        : True
bug_tracker:true
dvcs        : False

Use Has_option () to test if is option exists within a section.

From Configparser import safeconfigparser

parser = Safeconfigparser ()
parser.read (' Multisection.ini ')

For section in [' Wikis ', ' none ']:
    print '%s section exists:%s '% (section, parser.has_section (section)) for
    Cand Idate in [' username ', ' password ', ' URLs ', ' description ']:
        print '%s.%-12s  :%s '% (section, candidate, Parser.has _option (section, candidate))
    print

If The section does is not exist, has_option () returns

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.