python中的configparse學習筆記


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將內容寫入配置文件

實例如下:

配置文件:

[xiong]
name = xinog
age = 23
gender = male

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

python腳本:

#encoding:utf-8

from configparser import ConfigParser
cf=ConfigParser(allow_no_value=True)
cf.read('my.ini')

print(cf.sections())#獲取配置文件中的sections,結果:['xiong', 'ying']
print(cf.has_section('xiong'))#是否有xiong這個section,結果:True
print(cf.items('xiong'))#返回xiong這個section中的子項,結果:[('name', 'xinog'), ('age', '23'), ('gender', 'male')]
print(cf.options('xiong'))#返回xiong這個section中的變量,結果:['name', 'age', 'gender']
print(cf.has_option('xiong','age'))#判斷xiong這個section中是否有age這本變量
print(cf.get('xiong','age'))#獲取xiong這個section中age變量的值
# cf.remove_section('xiong')#移除xiong這個section
cf.add_section("cai")#添加一個叫cai的section
cf.set('cai','host','127.0.0.1')

#保存文件
cf.write(open('my.ini','w'))

被代碼更新后的配置文件:

[xiong]
name = xinog
age = 23
gender = male

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

[cai]
host = 127.0.0.1

 如果需要更詳細點,請參考:https://www.cnblogs.com/louhui/p/9089444.html#_label0


免責聲明!

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



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