python读写ini文件示例(python读写文件)

746次阅读  |  发布于5年以前

很类似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")

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8