一,百度百科
.ini 文件是Initialization File的縮寫,即初始化文件,是windows的系統
配置文件所采用的存儲格式,統管windows的各項配置,一般用戶就用windows提供的各項圖形化管理界面就可實現相同的配置了。但在某些情況,還是要直接編輯ini才方便,一般只有很熟悉windows才能去直接編輯。
開始時用於WIN3X下面,WIN95用
注冊表代替,以及后面的內容表示一個節,相當於注冊表中的鍵。
二,配置程序
示例ini配置文件(setting.ini)
1 [txtA] 2 name = comma,end,full,run 3 comma = 1000 4 end = 3 5 full = 2 6 run = 1 7 default_comma = 3 8 default_end = 3 9 default_full = 2 10 default_run = 1 11 12 [txtB] 13 name = comma,end,full,run 14 comma = 1000 15 end = 3 16 full = 2 17 run = 1 18 default_comma = 3 19 default_end = 3 20 default_full = 2 21 default_run = 1 22 23 [chinese] 24 name = volume,tones,speed,spokesman 25 volume = 5 26 tones = 5 27 speed = 5 28 spokesman = 1 29 default_volume = 5 30 default_tones = 5 31 default_speed = 5 32 default_spokesman = 1 33 34 [english] 35 name = volume,tones,speed,spokesman 36 volume = 5 37 tones = 5 38 speed = 5 39 spokesman = 1 40 default_volume = 5 41 default_tones = 5 42 default_speed = 5 43 default_spokesman = 1 44 45 [help] 46 47 [about]
示例ini配置文件操作程序1:
使用configparser函數,缺點:增刪、修改都是重寫ini文件操作
1 import configparser 2 import os 3 4 5 # *** 初始化配置文件路徑 *** # 6 curpath = os.path.dirname(os.path.realpath(__file__)) # 當前文件路徑 7 inipath = os.path.join(curpath, "setting.ini") # 配置文件路徑(組合、相對路徑) 8 9 # *** 數據讀取 *** # 10 conf = configparser.ConfigParser() 11 conf.read(inipath, encoding="utf-8") 12 # sections = conf.sections() # 獲取所有的sections名稱 13 # options = conf.options(sections[0]) # 獲取section[0]中所有options的名稱 14 # items = conf.items(sections[0]) # 獲取section[0]中所有的鍵值對 15 # value = conf.get(sections[-1],'txt2') # 獲取section[-1]中option的值,返回為string類型 16 # value1 = conf.getint(sections[0],'comma') # 返回int類型 17 # value2 = conf.getfloat(sections[0],'end') # 返回float類型 18 # value3 = conf.getboolean(sections[0],'run') # 返回boolen類型 19 20 # *** 刪除內容 *** # 21 # conf.remove_option(sections[0], "comma") 22 # conf.remove_section(sections[1]) 23 24 # *** 修改內容 *** # 25 conf.set('txtB', "comma", "1000") 26 conf.write(open(inipath, "r+", encoding="utf-8")) # r+模式 27 28 29 # print(conf.items(sections[0]) )
示例ini配置文件操作程序2:
使用configobj 函數
1 from configobj import ConfigObj 2 # *** 配置文件預處理 *** # 3 config = ConfigObj("setting.ini",encoding='UTF8') 4 5 # *** 讀配置文件 *** # 6 # print(config['txtB']) 7 # print(config['txtB']['name']) 8 9 # *** 修改配置文件 *** # 10 # config['txtB']['comma'] = "Mufasa" 11 # config.write() 12 13 # *** 添加section *** # 14 # config['txtC'] = {} 15 # config['txtC']['index0'] = "wanyu00" 16 # config.write()