ConfigParser-- 讀取寫入配置文件


基礎讀取配置文件

 

  • -read(filename)               直接讀取文件內容
  • -sections()                      得到所有的section,並以列表的形式返回
  • -options(section)            得到該section的所有option
  • -items(section)                得到該section的所有鍵值對
  • -get(section,option)        得到section中option的值,返回為string類型
  • -getint(section,option)    得到section中option的值,返回為int類型,還有相應的getboolean()和getfloat() 函數。

 

import ConfigParser,os

os.chdir('C:\\Users\\hito\\Desktop')
cf = ConfigParser.ConfigParser()

cf.read('test.ini')

a=cf.get('section1','option1')
print a+'a'


b=cf.getint('section1','option1')
print a+2

 

 

 

 

 

 

基礎寫入配置文件

 

 

 

  • -write(fp)                                                           將config對象寫入至某個 .init 格式的文件
  • -add_section(section)                                    添加一個新的section
  • -set( section, option, value                      對section中的option進行設置,需要調用write將內容寫入配置文件
  • -remove_section(section)                             刪除某個 section
  • -remove_option(section, option)                 刪除某個 section 下的 option

 

import ConfigParser,os

os.chdir('C:\\Users\\hito\\Desktop')


cf = ConfigParser.ConfigParser()

cf.add_section("section1")
cf.set("section1", "option1", 1)
cf.add_section("section2")
cf.set("section2", "option2", "value2")


# write to file
with open("test.ini","w+") as f:
    cf.write(f)

 


免責聲明!

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



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