標籤:類型 檔案格式 admin user .config igp conf res 取值
1.configparser模組介紹
configparser是用來讀取設定檔的模組,設定檔格式為:中括弧“[ ]”內包含的為section。section 下面為類似於key-value 的配置內容。
a.conf的檔案內容如下:
[user01]name = user01is_admin = Trueage = 34passwd = user123456[yxwang]name = yxwangage = 25passwd = 123456
取值:
import configparser#取值config=configparser.ConfigParser() #調用condigparser下的ConfigParser的方法,得到一個對象config.read(‘a.conf‘) #寫上設定檔的路徑,開啟檔案.print(config.sections()) #得到設定檔中的標題。 #[‘user01‘, ‘yxwang‘]print(config.options(config.sections()[0])) #查看某個標題下的配置項 等同於擷取user01下的配置項的keyres=config.get(‘user01‘,‘passwd‘)#查看某個標題下的某個配置項的值 注意這樣得到的數值是字串類型res1=config.getint(‘user01‘,‘age‘) #這樣得到的數值是一個字串.res1=config.getboolean(‘user01‘,‘is_admin‘) #這樣得到的數值是一個布爾值.print(res)
修改:
import configparserconfig=configparser.ConfigParser() #調用condigparser下的ConfigParser的方法,得到一個對象config.read(‘a.conf‘) #寫上設定檔的路徑,開啟檔案.config.remove_section(‘yxwang‘) #刪除一個標題,標題刪除了標題下的內容也一併刪除了config.remove_option(‘user01‘,‘age‘) #刪除一個標題下的內容config.add_section(‘user03‘) #新增一個標題config.set(‘user03‘,‘name‘,‘user03‘) #為指定標題插入內容config.write(open(‘a.conf‘,‘w‘)) #寫入檔案
python解析設定檔---configparser模組