標籤: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模組