python讀寫ini檔案樣本(python讀寫檔案)_python

來源:互聯網
上載者:User

很類似java的properties檔案

xml檔案

複製代碼 代碼如下:

db_config.ini
[baseconf]
host=127.0.0.1
port=3306
user=root
password=root
db_name=evaluting_sys
[concurrent]
processor=20

對應的python代碼

複製代碼 代碼如下:

#!/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")

得到結果:

複製代碼 代碼如下:

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

通用模組:支援命令列+import兩種形式
ini_op.py

複製代碼 代碼如下:

#!/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)

第二個樣本


複製代碼 代碼如下:

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()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.