Python 读取写入配置文件 —— ConfigParser

在项目中有时候需要读取配置文件,发现python有一个ConfigParser的东西,学习下。

首先奉上官网ConfigParser

1.支持配置文件格式

类似如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

首先是由一个sections(如 [DEFAULT] )引起,下面接类似“name = value”形式的key-value对。其实,接 “name : value”的形式也可以。

2.函数API
-read(filename)               直接读取文件内容
-sections()                      得到所有的section,并以列表的形式返回
-options(section)            得到该section的所有option
-items(section)                得到该section的所有键值对
-get(section,option)        得到section中option的值,返回为string类型
-getint(section,option)    得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置
  需要调用write将内容写入配置文件。

Example:

# -* - coding: UTF-8 -* -  
import ConfigParser  
#生成config对象  
conf = ConfigParser.ConfigParser()  
#用config对象读取配置文件  
conf.read("test.cfg")  
#以列表形式返回所有的section  
sections = conf.sections()  
print 'sections:', sections         #sections: ['sec_b', 'sec_a']  
#得到指定section的所有option  
options = conf.options("sec_a")  
print 'options:', options           #options: ['a_key1', 'a_key2']  
#得到指定section的所有键值对  
kvs = conf.items("sec_a")  
print 'sec_a:', kvs                 #sec_a: [('a_key1', '20'), ('a_key2', '10')]  
#指定section,option读取值  
str_val = conf.get("sec_a", "a_key1")  
int_val = conf.getint("sec_a", "a_key2")  

print "value for sec_a's a_key1:", str_val   #value for sec_a's a_key1: 20  
print "value for sec_a's a_key2:", int_val   #value for sec_a's a_key2: 10  

#写配置文件  
#更新指定section,option的值  
conf.set("sec_b", "b_key3", "new-$r")  
#写入指定section增加新option和值  
conf.set("sec_b", "b_newkey", "new-value")  
#增加新的section  
conf.add_section('a_new_section')  
conf.set('a_new_section', 'new_key', 'new_value')  
#写回配置文件  
conf.write(open("test.cfg", "w"))  
3.支持字段Interpolation

Python的ConfigParser Module中定义了3个类对INI文件进行操作。

分别是RawConfigParser、ConfigParser、SafeConfigParser。

RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的解析。

配置文件test.cfg
[plain] view plain copy
[portal]  
url = http://%(host)s:%(port)s/Portal  
host = localhost  
port = 8080 

使用RawConfigParser:

[python] view plain copy
import ConfigParser  

conf = ConfigParser.RawConfigParser()  
print "use RawConfigParser() read"  
conf.read("test.cfg")  
print conf.get("portal", "url")  

print "use RawConfigParser() write"  
conf.set("portal", "url2", "%(host)s:%(port)s")  
print conf.get("portal", "url2")  

得到输出

[plain] view plain copy
use RawConfigParser() read  
http://%(host)s:%(port)s/Portal  
use RawConfigParser() write  
%(host)s:%(port)s  

改用ConfigParser

[python] view plain copy
import ConfigParser  

conf = ConfigParser.ConfigParser()  
print "use RawConfigParser() read"  
conf.read("test.cfg")  
print conf.get("portal", "url")  

print "use RawConfigParser() write"  
conf.set("portal", "url2", "%(host)s:%(port)s")  
print conf.get("portal", "url2")  

得到输出

[plain] view plain copy
use RawConfigParser() read  
http://localhost:8080/Portal  
use RawConfigParser() write  
localhost:8080  

改用SafeConfigParser,效果与ConfigParser相同

[python] view plain copy
import ConfigParser  

conf = ConfigParser.SafeConfigParser()  
print "use RawConfigParser() read"  
conf.read("test.cfg")  
print conf.get("portal", "url")  

print "use RawConfigParser() write"  
conf.set("portal", "url2", "%(host)s:%(port)s")  
print conf.get("portal", "url2")  
4.支持注释#与;

config文件中可以有注释,以#或者;开始,但强烈建议从空行开始写注释,否则会可能导致一些隐性错误

[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values

[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true

[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
    I sleep all night and I work all day

[No Values]
key_without_value
empty string value here =

[You can use comments]
# like this
; or this

# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.

    [Sections Can Be Indented]
        can_values_be_as_well = True
        does_that_mean_anything_special = False
        purpose = formatting for readability
        multiline_values = are
            handled just fine as
            long as they are indented
            deeper than the first line
            of a value
        # Did I mention we can indent comments, too?

你可能感兴趣的:(python学习)