python读取配置文件使用_python 使用 ConfigParser 读取和修改INI配置文件
在程序開發中,使用獨立的配置文件來配置一些參數常見且方便,配置文件的解析或修改并不復雜,在python里更是如此,在官方發布的庫中就包含有做這件事情的庫,那就是ConfigParser,ConfigParser模塊解析的配置文件的格式類似ini的配置文件格式,就是文件由多個section構成,每個section下又有多個配置項.
下面就以一個具體的腳本實例,來說明這個模塊的使用方法:
腳本文件名: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
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的python读取配置文件使用_python 使用 ConfigParser 读取和修改INI配置文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tablednd保存 php,JQuer
- 下一篇: python 片段_python片段程序