温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

【Python模块】configparser模块

发布时间:2020-06-29 06:00:14 来源:网络 阅读:959 作者:等你的破船 栏目:编程语言

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

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

结果:

http://192.168.0.1':8000/Portal

'section name' in configparser实例

判断实例中是否有section

返回True或False

DEAFUALT只能用此方式判断

‘DEAFULT’只能用此方法判断




####例一:
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'])

 

 

 

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI