python读取配置文件使用_python 使用 ConfigParser 读取和修改INI配置文件
在程序開發(fā)中,使用獨(dú)立的配置文件來配置一些參數(shù)常見且方便,配置文件的解析或修改并不復(fù)雜,在python里更是如此,在官方發(fā)布的庫中就包含有做這件事情的庫,那就是ConfigParser,ConfigParser模塊解析的配置文件的格式類似ini的配置文件格式,就是文件由多個(gè)section構(gòu)成,每個(gè)section下又有多個(gè)配置項(xiàng).
下面就以一個(gè)具體的腳本實(shí)例,來說明這個(gè)模塊的使用方法:
腳本文件名:chconfig.py 代碼如下:
#!/usr/bin/python
# -*- coding:gbk -*-
# Author: Droeny.zhao
# Version: 2010-04-08
import sys
import ConfigParser
def getinfo(COLUMN,ITEM):
conf=ConfigParser.ConfigParser()
CONFIGNAME = 'game.ini'
if os.path.isfile(CONFIGNAME):
conf.read(CONFIGNAME)
conf.sections()
try:
return conf.get(COLUMN,ITEM)
except ConfigParser.NoOptionError, e:
print 'Wanning:',e
sys.exit()
else:
print 'Wanning: "%s" is not exists, you must appoint the absolute path of config file with -p or -c.'%(CONFIGNAME)
sys.exit()
def setinfo(COLUMN,ITEM,VALUE):
conf=ConfigParser.ConfigParser()
CONFIGNAME = 'game.ini'
if os.path.isfile(CONFIGNAME):
conf.read(CONFIGNAME)
conf.sections()
try:
conf.set(COLUMN,ITEM,VALUE)
conf.write(open(CONFIGNAME, 'w'))
except ConfigParser.NoOptionError, e:
print 'Wanning:',e
sys.exit()
else:
print 'Wanning: "%s" is not exists, you must appoint the absolute path of config file with -p or -c.'%(CONFIGNAME)
sys.exit()
if __name__ == '__main__':
print getinfo('Account','DBName')
setinfo('Account','DBName','GameDB')
print getinfo('Account','DBName')
配置文件:game.ini 代碼如下:
[Account]
username = test01
servername = 192.168.0.1
password = 123456
dbname = AccountDB
[Database]
username = test02
servername = 192.168.0.2
password = 123456
dbname = GameDB
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的python读取配置文件使用_python 使用 ConfigParser 读取和修改INI配置文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tablednd保存 php,JQuer
- 下一篇: CSS中背景颜色、背景图片、渐变色、背景