溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

【Python模塊】configparser模塊

發(fā)布時(shí)間:2020-06-29 06:00:14 來源:網(wǎng)絡(luò) 閱讀:970 作者:等你的破船 欄目:編程語言

configparser模塊:

 是python標(biāo)準(zhǔn)庫用來解析配置文件的模塊。

格式:

    section:使用[]標(biāo)記section名

    :或= :使用:或=賦值

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

    同一個(gè)項(xiàng)可以多個(gè)值:

ip:'192.168.1.11','192.168.1.12','192.168.1.13'  #待測試

    read配置文件時(shí),會(huì)自動(dòng)把參數(shù)名變成小寫


    一個(gè)section下有多個(gè)相同的參數(shù),只能讀取最后一個(gè)


    




方法、屬性名參數(shù)作用示例
ConfigParser()

創(chuàng)建configpaser實(shí)例

read(filename)
filename: ini格式的文件名
打開ini格式的文件

sections()

以list形式返回所有section

items(section name)

section name:

指定section名字

把指定section的所有參數(shù)和值的元組,以list形式返回

options(section name)

section name:

指定section名字

以list形式,返回section里所有參數(shù)名
get[section name][args name]

section name:指定section名字

argsname:指定參數(shù)名

返回section的單個(gè)參數(shù)值。
getint()\getboolean()\getfloat()


add_section(section_name)section_name:指定section名字添加一個(gè)新的section
set(section_name,args_name,value)

section_name:指定section名字

args_name:指定參數(shù)名

value:設(shè)定參數(shù)的值

設(shè)定具體的參數(shù)值。
remove_section(section_name)section_name:指定section名字刪除指定的section
remove_option(section_name,args_name)

section_name:指定section名字

args_name:指定參數(shù)名

刪除section中的args項(xiàng)
clear()
清空除DEAFULT外所有section
write(open(file_name,'w'))open(file_name,'w')):以寫模式打開一個(gè)文件把以上的編輯完成的信息存到file_name
has_section(section name)section name:指定section

尋找配置文件中指定的section

找到返回True,找不到返回False

進(jìn)階操作:


單個(gè)參數(shù)值是多行除首行外,其它行加一個(gè)空格

args = “行1

  行2”

結(jié)果:

行1

行2

參數(shù)值帶變量url = http://%(host)s:%(port)s/Portal

[web]

host = '192.168.0.1'

port = 8000

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

結(jié)果:

http://192.168.0.1':8000/Portal

'section name' in configparser實(shí)例

判斷實(shí)例中是否有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問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI