【Python模块】configparser模块

configparser模块:

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

格式:

    section:使用[]标记section名

    :或= :使用:或=赋值

[websv]
ip:'192.168.1.10'
port:443
name = 'root'
pw = 'root1990'
定义:
websv叫section

    同一个项可以多个值:

ip:'192.168.1.11','192.168.1.12','192.168.1.13'  #待测试

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


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


    




方法、属性名 参数 作用 示例
ConfigParser()

创建configpaser实例
read(filename)
filename: ini格式的文件名
打开ini格式的文件
sections()

以list形式返回所有section
items(section name)

section name:

指定section名字

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

section name:

指定section名字

以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)

section_name:指定section名字

args_name:指定参数名

value:设定参数的值

设定具体的参数值。
remove_section(section_name) section_name:指定section名字 删除指定的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
进阶操作:
单个参数值是多行 除首行外,其它行加一个空格

args = “行1

  行2”

结果:

行1

行2

参数值带变量 url = http://%(host)s:%(port)s/Portal

[web]

host = '192.168.0.1'

port = 8000

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

结果:

http://192.168.0.1':8000/Portal

####例一:
import configparser

config = configparser.ConfigParser()
config.read('example.ini')

#section_name = ['webserver']
#args_name = ['ip', 'port', 'url']
config.add_section('webserver')
config.set('webserver','ip','192.168.0.1')
config.set('webserver','port',8000)

config.set('webserver','url','http//:%(ip)s:%(port)s')
config.write(open('example.ini','w'))

print(config.sections())
print(config.options())
print(config.items())
print(config.get['webserver']['url'])

猜你喜欢

转载自blog.51cto.com/yishi/2135535