Python 讀取配置文件


Python 讀取寫入配置文件很方便,可使用內置的 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
import os
cf = configparser.ConfigParser()
path = os.path.abspath('./rsp.conf')
cf.read(path)
host = cf.get('bluetooth', 'host')
base_url = cf.get('bluetooth','base_url')
print(host,base_url)
print(cf.sections())

運行結果

 


免責聲明!

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



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