本文實例講述了Python實現讀寫INI配置文件的方法。分享給大家供大家參考,具體如下:
# -*- coding: utf-8 -*- import ConfigParser import os '''讀寫配置文件的類 [section] logpath = D:\log\ imageminsize = 200 ''' class ConfigFile: '''構造函數:初始化''' def __init__(self,fileName): fileName = unicode(fileName,'utf8') self.flag = False if os.path.isfile(fileName): self.fileName = fileName self.cf = ConfigParser.ConfigParser() self.cf.read(self.fileName) self.flag = True '''獲取節為section,鍵值為Key的值''' def GetValue(self,Section, Key): if self.flag: try: result = self.cf.get(Section, Key) return result except Exception,e: print e return "" else: return "" def SetValue(self,Section, Key,Value): if self.flag: try: self.cf.set(Section, Key, Value) self.cf.write(open(self.fileName, "w")) except Exception,e: print e return "" #測試代碼 configfile = os.path.join(os.getcwd(),'config.conf') cf = ConfigFile(configfile) print cf.GetValue("section","logpath") cf.SetValue("section","imageminsize","200")
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python函數使用技巧總結》、《Python面向對象程序設計入門與進階教程》、《Python數據結構與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。