Python模塊之configpraser
一. configpraser簡介
用於處理特定格式的文件,其本質還是利用open來操作文件。
配置文件的格式:
使用"[]"內包含section,section下為類似key-value的配置內容(例如:samba配置文件)
G:\Python項目實戰\模塊\configparser>start example.txt #基於windows平台
# 注釋1 ;注釋2 [global] #節點 workgroup = WORKGROUP #值(key-value) security = share
maxlog = 50 [public] comment = stuff public = True
pi = 3.1415926
二. configpraser初始化
使用時必須先初始化並讀取配置文件
import configparser config = configparser.ConfigParser() config.read('example.txt',encoding='utf-8')
三. configpraser常用方法
1. 獲取所有節點:
ret = config.sections() #讀取配置文件里所有的"[]"信息 print(ret) #輸出: ['global', 'public']
2. 獲取指定節點下的所有鍵值對:
ret = config.items('global')#獲取指定節點的所有鍵值對 print(ret) #輸出: [('workgroup', 'WORKGROUP'), ('security', 'share'), ('maxlog', '50')]
3. 獲取指定節點下的所有鍵:
ret = config.options('public')#指定節點下的所有鍵 print(ret) #輸出: ['comment', 'public', 'pi']
4. 獲取指定節點下指定key的值:
ret = config.get('global','workgroup')#獲取指定節點下key的值 # ret = config.getint('global','maxlog')#獲取指定節點下key值,必須為整數否則報錯 # ret = config.getfloat('public','pi')#獲取指定節點下key值,必須為浮點數否則報錯 # ret = config.getboolean('public','public')#獲取指定節點下key值,必須為布爾值否則報錯 print(ret)
5. 檢查,添加,刪除節點
#檢查 check = config.has_section('global') #檢查此節點下是否有值,返回布爾值 print(check) #輸出: True #添加節點 config.add_section('local') #添加到內存 config.write(open('example.txt','w')) #寫入文件中 ret = config.sections() print(ret) #輸出: ['global', 'public', 'local'] #刪除節點 config.remove_section('local') #刪除節點 config.write(open('example','w'))#重新寫入文件 ret = config.sections() print(ret) #輸出: ['global', 'public']
6. 檢查,刪除,設置指定組內的鍵值對
#檢查 check = config.has_option('public','comment')#檢查節點下的某個鍵,返回布爾值 print(check) 輸出: True #刪除 config.remove_option('global','workgroup') config.write(open('example.txt','w')) ret = config.options('global') print(ret) #輸出: ['security', 'maxlog'] #設置指定節點內的鍵值對 ret1 = config.get('global','maxlog') print(ret1) config.set('global','maxlog','100') config.write(open('example.txt','w')) ret2 = config.get('global','maxlog') print(ret2) #輸出: 50 100
