python读取ini_python文件操作(一)ConfigParser模块读写ini文件

Python的ConfigParser Module 中定义了3个类对INI文件进行操作。分别是RawConfigParser、ConfigParser、SafeConfigParser。 RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的 解析。

一、类和方法

1、RawConfigParser实例方法

defaults() :返回全部示例中所以defaults。

sections() :返回有效的section列表,DEFAULT不包含在列表中。

add_section(section) :为实例添加一个section,如果给定的section名已经存在,将抛出DuplicateSectionError异常。

has_section(section) :判断给定的section名在配置文件中是否存在,DEFAULT section不包括。

options(section) :返回给定的section下的所有可用option的列表。

has_option(section, option) :如果section存在,并包含给定的option,返回true,放在返回false, 1.6版本新增。

read(filenames) :尝试解析文件列表,如果解析成功返回文件列表。如果filenames是string或Unicode

string,将会按单个文件来解析。如果在filenames中的文件不能打开,该文件将被忽略。这样设计的目的是,让你能指定本地有可能是配置文件的

列表(例如,当前文件夹,用户的根目录,及一些全系统目录),所以在列表中存在的配置文件都会被读取。如果文件都不存在,那么ConfigParser实

例会包含空数据集。一个需要从配置文件读取初始化数据的应用程序,应该使用readfp()方法来加载所需要的文件,之后可以使用read()方法来获取

任何可能的文件:2.4版本之后,返回成功解析的文件列表。

readfp(fp[, filename]) :从文件或fp(值使用该对象的readline()方法)中的似文件类读取并解析配置数据,如果filename被省略,fp有一个name属性,该属性用于获取filename 。

get(section, option) :获取section下option的值。

getint(section, option) :强制指定section下的option的值,作为Int类型返回的方便方法。

getfloat(section, option) :强制section下的option值,作为float类型返回的方法方法。

getboolean(section, option) :强制section下的option值,作为布尔类型返回的方法方法。注意可接受的option的true值有“1”,“yes”,“true”及

“on”,可接受的false值有“0”,“no”,“false”,“off”。字符串值不检测大小写,其他值会抛出ValueError异常。

itmes(section) :返回给定section下的所以option的(name, value)对列表。

set(section, option, value) :如果给定的setion存在,为option设定给定的值;否则抛出NoSectionError异常。当可能使用RawConfigParser(或者

ConfigParser的参数raw为true)来在内部存储非字符串值,所以功能(包括填补和输出到文件)只能使用字符串值来归档。1.6版本新增。

write(fileobject) :将配置表示写入指定文件类,该表示以后可以通过调用read()来解析,1.6版本新增。

remove_option(section, option) :从指定section中删除指定option,如果section不存在,抛出NoSectionError异常;如果option存在,则删除,并返回True;否则返回false。1.6版本新增。

remove_section(section) :从配置文件中删除指定的section,如果section确实存在,返回true,否则返回false。

optionxform(option) :将输入文件中,或客户端代码传递的option名转化成内部结构使用的形式。默认实现返回option的小写形式;子类可能重写该方法或客户端代码可能将该方法作为实例的属性,以此来影响它的行为。将此用于str(),例如,会使option名称大小写敏感。

2、ConfigParser对象方法

ConfigParser类扩展了RawConfigParser的一些接口方法,添加了一些可选参数。

get(section, option [, raw[, vars]]) :获取给定section下的option的值,所以“%”占位符在返回值中被填补,基于构造时传递的默认值,就像option,vars也被提供,除非raw参数为true。

items(section, [, raw[, vars]]) :返回给定section下的所以option的(name, value)对列表。可选参数同get方法,2.3版本新增。

3、SafeConfigParser对象中的方法

SafeConfigParser类实现了ConfigParser相同的接口,新增如下方法:

set(section, option, value) :如果给定的section存在,给option赋值;否则抛出NoSectionError异常。Value值必须是字符串(str或unicode);如果不是,抛出TypeError异常,2.4版本新增。

二、使用示例

dbconf.ini文件

[baseconf]

host=127.0.0.1

port=3306

user=root

password=root

db_name=evaluting_sys

[concurrent]

processor=20

读写代码:

import sys,os

import ConfigParser

def test(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__":

test("../conf/db_config.ini")

也可以按如下用法处理

muti_site.ini

[site]

url = http://www.361way.com/

username = 361way

password = nothing

[site2]

url = http://www.91it.org/

username = 91it

password = org

读取代码如下:

from ConfigParser import SafeConfigParser

parser = SafeConfigParser()

parser.read('multisection.ini')

for section_name in parser.sections():

print 'Section:', section_name

print ' Options:', parser.options(section_name)

for name, value in parser.items(section_name):

print ' %s = %s' % (name, value)

在对ini文件里的不存在的key进行取值时,如取username1,由于不存在会报错,针对该问题,可以使用下面的一个类进行处理:

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] #值从0-4,第5个值的下标为4

write_config(config_file_path, field, key, value)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值