Example of reading and writing INI files using python (reading and writing files using python)-Python tutorial

Source: Internet
Author: User
The project uses a database, which is used in multiple places and cannot be hard-coded. Ython supports reading INI files and uses the INI file in the project. The following is an example similar to the properties file of java.

Xml file

The 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

Corresponding python code

The code is 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 ("base conf", "db_pass", "123456 ")
Cf. write (open ("config_file_path", "w "))
If _ name _ = "_ main __":
F = Db_Connector ("../conf/db_config.ini ")

Expected result:

The code is as follows:


Section: ['context', 'baseconf']
Options: ['host', 'DB _ name', 'user', 'password', 'port']
Db: [('host', '123. 0.0.1 '), ('Db _ name', 'evaluting _ SYS'), ('user', 'root'), ('password', 'root '), ('port', '123')]
127.0.0.1 3306 root

Common Module: supports command line and import
Ini_op.py

The code is 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 t:
Result = ""
Return result
Def set (self, filed, key, value ):
Try:
Self. cf. set (field, key, value)
Cf. write (open (self. path, 'w '))
Except t:
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 t:
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 t:
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)

Example 2


The code is 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 ()

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.