Python read/write. ini configuration file

Source: Internet
Author: User

# Coding = UTF-8
Import configparser

Class myclass (object ):
Retrieve configuration file
Def _ init _ (Self ):
Self. Path = "../config. ini"
Self. cf = configparser. configparser ()
Self. Cf. Read (self. Path)
Except t:
Print "failed t"
Def get (self, section, option ):
If not self. Cf. has_section (Section): Return
If not self. Cf. has_option (section, option): Return
S = self. Cf. Get (section, option)
Return s
Def getdefault (self, key ):
AC = "sysconf"
Return self. Get (AC, key)

Def add (self, section, option, value ):
If self. Cf. has_section (Section): # Append content
If not self. Cf. has_option (section, option ):
Self. Cf. Set (section, option, value)
Self. Save ("R + ")
Self. Update (section, option, value)
Else: # Add a new section
If self. Cf. has_option (section, option ):
Self. Update (section, option, value)
Self. Cf. add_section (Section)
Self. Cf. Set (section, option, value)
Self. Save ("W ")

Def Update (self, section, option, value ):
Self. Cf. Set (section, option, value)
Self. Save ("W ")

Def removesection (self, Section ):
Self. Cf. remove_section (Section)
Self. Save ("W ")

Def removeoption (self, section, option ):
Self. Cf. remove_option (section, option)
Self. Save ("W ")
Def save (self, OP ):
Self. Cf. Write (open (self. Path, OP ))
If _ name _ = "_ main __":
M = myclass ()

Section = "ddd3"
Option = "test1322"

M. removesection (Section)
# M. removeoption (section, option)
# M. Add (section, option, "dsfsdf111 ")
# M. Update (section, option, "789456 qaaa ")

Related Article

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: 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.