天天看点

【Python模块】configparser模块

configparser模块:

 是python标准库用来解析配置文件的模块。

格式:

    section:使用[]标记section名

    :或= :使用:或=赋值

    同一个项可以多个值:

    read配置文件时,会自动把参数名变成小写

    一个section下有多个相同的参数,只能读取最后一个

方法、属性名

参数

作用

示例

configparser()

创建configpaser实例

read(filename)

filename: ini格式的文件名

打开ini格式的文件

sections()

以list形式返回所有section

items(section name)

section name:

指定section名字

把指定section的所有参数和值的元组,以list形式返回

options(section name)

以list形式,返回section里所有参数名

get(section name,args name)

section name:指定section名字

argsname:指定参数名

返回section的单个参数值。

getint()\getboolean()\getfloat()

add_section(section_name)

section_name:指定section名字

添加一个新的section

set(section_name,args_name,value)

args_name:指定参数名

value:设定参数的值

设定具体的参数值。

remove_section(section_name)

删除指定的section

remove_option(section_name,args_name)

section_name:指定section名字

args_name:指定参数名

删除section中的args项

clear()

清空除deafult外所有section

write(open(file_name,'w'))

open(file_name,'w')):以写模式打开一个文件

把以上的编辑完成的信息存到file_name

has_section(section name)

section name:指定section

寻找配置文件中指定的section

找到返回true,找不到返回false

进阶操作:

单个参数值是多行

除首行外,其它行加一个空格

args = “行1

  行2”

结果:

行1

行2

参数值带变量

url = http://%(host)s:%(port)s/portal

[web]

host = '192.168.0.1'

port = 8000

http://192.168.0.1':8000/portal

'section name' in configparser实例

判断实例中是否有section

返回true或false

deafualt只能用此方式判断

‘deafult’只能用此方法判断