【Python模組】configparser模組

來源:互聯網
上載者:User

標籤:int   檔案名稱   regexp   格式   server   刪除   完成   rgb   讀取   

configparser模組:

 是python標準庫用來解析設定檔的模組。

格式:

    section:使用[]標記section名

    :或= :使用:或=賦值

[websv]ip:'192.168.1.10'port:443name = '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 configparserconfig = 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'])

 

【Python模組】configparser模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.