from configparser import ConfigParser fp = 'conf.ini' #定義配置文件名 conf = ConfigParser() #實例化 conf.read(fp) # 打開conf conf.add_section('Section1') #添加conf節點 conf.set('Section1', 'name', 'jack') #添加值 conf.set('Section1', 'age', '23') conf.set('Section1', 'worker', 'CEO') conf.add_section('Section2') #添加conf節點 conf.set('Section2', 'name', 'rose') #添加值 conf.set('Section2', 'age', '21') conf.set('Section2', 'worker', 'CCC') with open(fp, 'w') as fw: #循環寫入 conf.write(fw) ''' [Section1] name = jack age = 23 worker = CEO ''' #讀取配置文件 from configparser import ConfigParser fp = 'conf.ini' #定義配置文件名 conf = ConfigParser() #實例化 conf.read(fp) # 打開conf name = conf.get('Section1','name') print(name) ''' 1)讀取配置文件 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() 函數。 ''' section= conf.sections() print(section) option =conf.options('Section1') print(option) item=conf.items('Section1') print(item) #改寫操作 conf.set('Section1', 'name', 'jackadam') #設置為新值 with open(fp, 'w') as fw: #循環寫入 conf.write(fw) from configparser import ConfigParser #重新讀取 fp = 'conf.ini' #定義配置文件名 conf = ConfigParser() #實例化 conf.read(fp) # 打開conf name = conf.get('Section1','name') print(name)