溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python實(shí)現(xiàn)讀寫INI配置文件的方法示例

發(fā)布時(shí)間:2020-08-25 15:51:53 來源:腳本之家 閱讀:169 作者:shaomine 欄目:開發(fā)技術(shù)

本文實(shí)例講述了Python實(shí)現(xiàn)讀寫INI配置文件的方法。分享給大家供大家參考,具體如下:

# -*- coding: utf-8 -*-
import ConfigParser
import os
'''讀寫配置文件的類
[section]
logpath = D:\log\
imageminsize = 200
'''
class ConfigFile:
  '''構(gòu)造函數(shù):初始化'''
  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
  '''獲取節(jié)為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")

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python函數(shù)使用技巧總結(jié)》、《Python面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對大家Python程序設(shè)計(jì)有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI