1. 程式人生 > >Python學習筆記21(讀取配置文件)

Python學習筆記21(讀取配置文件)

文件 class strong color () for 新的 -i .config

1、基本的讀取操作

  • -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() 函數。
#peizhi.ini

[section1111]
name = zy
age = 23

[section2222]
ip = 192.168.1.1
port = 8080
import configparser   #引入必要的包

cf = configparser.ConfigParser()  #實例化configparser對象
cf.read("peizhi.ini")       #讀取配置文件

s = cf.sections()   #讀取所有的section
i = cf.items(section2222) #讀取該section下所有的鍵值對
o = cf.options(
section2222) #讀取該section下的所有option,即鍵 k = cf.get(section2222,ip) #得到section中該option的值 has_sec = cf.has_option(section2222,name) #判斷該鍵值對是否存在

2、基本的寫操作

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

Python學習筆記21(讀取配置文件)