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())
運行結果

