python读取配置文件使用_python 使用 ConfigParser 读取和修改INI配置文件

本文介绍了Python中ConfigParser模块的使用,通过示例脚本`chconfig.py`展示了如何读取和修改配置文件`game.ini`的内容。配置文件由多个section组成,每个section下包含多个配置项。脚本提供了获取和设置配置信息的函数,并处理了文件不存在或选项错误的情况。
摘要由CSDN通过智能技术生成

在程序开发中,使用独立的配置文件来配置一些参数常见且方便,配置文件的解析或修改并不复杂,在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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值