Python read-write INI file example (Python read-write file)

Source: Internet
Author: User
Very similar to the Java properties file

XML file

Copy CodeThe code is as follows:


Db_config.ini
[Baseconf]
host=127.0.0.1
port=3306
User=root
Password=root
Db_name=evaluting_sys
[Concurrent]
Processor=20

The corresponding Python code

Copy the Code code as follows:


#!/usr/bin/python
#-*-Coding:utf-8-*-
#author: LINGYUE.WKL
#desc: Use to DB Ops
#---------------------
#2012 -02-18 Created

#---------------------
Import Sys,os
Import Configparser

Class Db_connector:
def __init__ (self, Config_file_path):
CF = Configparser.configparser ()
Cf.read (Config_file_path)

s = cf.sections ()
print ' section: ', S

o = cf.options ("baseconf")
print ' Options: ', O

v = cf.items ("baseconf")
print ' db: ', V

Db_host = Cf.get ("baseconf", "host")
Db_port = Cf.getint ("baseconf", "Port")
Db_user = Cf.get ("baseconf", "user")
Db_pwd = Cf.get ("baseconf", "password")

Print Db_host, Db_port, Db_user, db_pwd

Cf.set ("baseconf", "Db_pass", "123456")
Cf.write (Open ("Config_file_path", "w"))
if __name__ = = "__main__":
f = Db_connector (".. /conf/db_config.ini ")

Get results:
Copy the Code code as follows:


Section: [' Concurrent ', ' baseconf ']
Options: [' Host ', ' db_name ', ' user ', ' password ', ' Port ']
DB: [(' Host ', ' 127.0.0.1 '), (' db_name ', ' Evaluting_sys '), (' User ', ' root '), (' Password ', ' root '), (' Port ', ' 3306 ')]
127.0.0.1 3306 Root root

Universal module: Support Command line +import two forms
ini_op.py
Copy the Code code as follows:


#!/usr/bin/python
#-*-Coding:utf-8-*-
#author: LINGYUE.WKL
#desc: Use to read ini
#---------------------
#2012 -02-18 Created
#2012 -09-02 changed for class support

#---------------------
Import Sys,os,time
Import Configparser


Class Config:
def __init__ (self, Path):
Self.path = Path
SELF.CF = Configparser.configparser ()
Self.cf.read (Self.path)
def get (Self, field, key):
result = ""
Try
result = self.cf.get (field, key)
Except
result = ""
return result
def set (self, filed, key, value):
Try
Self.cf.set (field, key, value)
Cf.write (Open (Self.path, ' W '))
Except
Return False
Return True
def read_config (Config_file_path, field, key):
CF = Configparser.configparser ()
Try
Cf.read (Config_file_path)
result = cf.get (field, key)
Except
Sys.exit (1)
return result

def write_config (Config_file_path, field, key, value):
CF = Configparser.configparser ()
Try
Cf.read (Config_file_path)
Cf.set (field, key, value)
Cf.write (Open (Config_file_path, ' W '))
Except
Sys.exit (1)
Return True

if __name__ = = "__main__":
If Len (SYS.ARGV) < 4:
Sys.exit (1)

Config_file_path = sys.argv[1]
field = Sys.argv[2]
Key = Sys.argv[3]
If Len (sys.argv) = = 4:
Print Read_config (config_file_path, field, key)
Else
Value = Sys.argv[4]
Write_config (Config_file_path, field, key, value)

A second example


Copy the Code code as follows:


Import OS
Import Configparser

def main ():
CP = Configparser.configparser ()
CF = open (U "In.ini")
CP.READFP (CF)

secs = Cp.sections ()
Print cp.sections ()

For sec in secs:
OPTs = cp.options (sec)
For opt in opts:
val = cp.get (sec, opt)
Val + = "Test ..."
Cp.set (sec, opt, Val)

Cp.write (Open ("Out.ini", "w"))

if __name__ = = ' __main__ ':
Main ()

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