python解析配置文件(.ini)


在開發過程中,有一類文件是常用的,比如配置或叫初始化文件(.ini)。文件里面可以存放主機ip地址、用戶名/密碼及其他一些有關項目的公共信息。

這類文件的處理一般比較簡單,比起excel、JSON等數據文件來說應該比較短小。因為數據文件是面對數據分析的,而配置文件經常作為全局變量。

python的configparse用於處理配置文件。目前感覺configparse比json的好處是配置文件簡單清晰,但不足之處是無法實現
多層嵌套。
configparse主要用於在python中進行配置文件的讀取。讀取后的數據結構是列表,可以按照列表進行處理。
配置文件不用區分數據類型。最后都按照字符串讀取。

基本的讀取配置文件模塊函數:
-read(filename) 直接讀取ini文件內容
-sections() 得到所有的section,並以列表的形式返回
-options(section) 得到該section的所有option
-items(section) 得到該section的所有鍵值對
-get(section,option) 得到section中option的值,返回為string類型
-getint(section,option) 得到section中option的值,返回為int類型,還有相應的getboolean()和getfloat() 函數
-write(filename,'w')) 保存配置cf.write(open(filename,'w'))
-add_section(section) 添加一個新的section
-set( section, option, value) 對section中的option進行設置,需要調用write將內容寫入配置文件
先構造一個配置文件my.ini。內容如下:
[xiong]
name = xiong
age = 23
gender = male

[ying]
name = ying
age = 24
gender = female

[cai]
host_ip = 127.0.0.1
host_name = test1
user1 = root
user1_passwd = 123456
user2 = hdfs
user2_passwd = abcdef
[host]
IP=127.0.0.1
PORT=8090

[auth]
user='Alex'
passwd='123456'
View Code

解析該配置文件,實例如下:
 1 from configparser import ConfigParser
 2 cf=ConfigParser(allow_no_value=True)
 3 cf.read(r'doc_file/my.ini')
 4 
 5 print(cf.sections())#獲取配置文件中的sections,結果:['xiong', 'ying', 'cai', 'host', 'auth']
 6 print("sections-0",cf.sections()[0])
 7 for section in cf.sections():   #對列表進行遍歷
 8     print(section)      #配置文件的第一層[]中內容,eg.xiong
 9     print(cf.items(section))    #配置文件中[]下的內容。依然是列表。
10 print(cf.has_section('xiong'))#是否有xiong這個section,結果:True
11 print(cf.items('xiong'))#返回xiong這個section中的子項,結果:[('name', 'xinog'), ('age', '23'), ('gender', 'male')]
12 print(cf.options('xiong'))#返回xiong這個section中的變量,結果:['name', 'age', 'gender']
13 print(cf.has_option('xiong','age'))#判斷xiong這個section中是否有age這個變量
14 
15 #這個cf.get方法才是常用的方法,以上方法只是在遍歷或者其他通用方式下用。
16 #因為配置文件是可讀的,用get方法直接獲取host、ip信息即可。
17 print(cf.get('xiong','age'))#獲取xiong這個section中age變量的值:23
18 print(cf.get('host','ip'))
19 #>>>127.0.0.1,這個功能才是最實際的用途。這也可以看出此功能比json的略有優勢:直觀、方便讀取
20 print("0:",cf.items('cai')[0])
21 # cf.remove_section('xiong')#移除xiong這個section
22 # cf.add_section("cai-3")#添加一個叫cai的section
23 # cf.set('cai-3','host','192.168.0.2')
24 # #保存文件
25 cf.write(open(r'doc_file/my.ini.bak','w'))
View Code
 
        

以上代碼中,將修改的內容存入另一個文件。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM