Python之配置文件讀寫
阿新 • • 發佈:2017-12-11
con nbsp 獲取 如果 option 創建 函數 添加 ans ConfigParser模塊
一、創建配置文件
在D盤建立一個配置文件,名字為:test.ini
內容如下:
[baseconf]
host=127.0.0.1
port=3306
user=root
password=root
db_name=gloryroad
[test]
ip=127.0.0.1
int=1
float=1.5
bool=True
註意:要將文件保存為ansi編碼,utf-8編碼會報錯
文件中的[baseconf]為section
二、讀配置文件
import ConfigParser
cf=ConfigParser.ConfigParser()
cf.read(path) 讀配置文件(ini、conf)返回結果是列表
cf.sections() 獲取讀到的所有sections(域),返回列表類型
cf.options(‘sectionname‘) 某個域下的所有key,返回列表類型
cf.items(‘sectionname‘) 某個域下的所有key,value對
value=cf.get(‘sectionname‘,‘key‘) 獲取某個yu下的key對應的value值
cf.type(value) 獲取的value值的類型
(1)getint(section, option)
獲取section中option的值,返回int類型數據,所以該函數只能讀取int類型的值。
(2)getboolean(section, option)
獲取section中option的值,返回布爾類型數據,所以該函數只能讀取boolean類型的值。
(3)getfloat(section, option)
獲取section中option的值,返回浮點類型數據,所以該函數只能讀取浮點類型的值。
(4)has_option(section, option)
檢測指定section下是否存在指定的option,如果存在返回True,否則返回False。
(5)has_section(section)
檢測配置文件中是否存在指定的section,如果存在返回True,否則返回False。
三、動態寫配置文件
cf.add_section(‘test‘) 添加一個域
cf.set(‘test3‘,‘key12‘,‘value12‘) 域下添加一個key value對
cf.write(open(path,‘w‘)) 要使用‘w‘
Python之配置文件讀寫