欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python实现的ini文件操作类分享

程序员文章站 2023-03-29 21:29:24
类代码: # -*- coding:gbk -*- import configparser, os class inifile: def __init_...

类代码:

# -*- coding:gbk -*-
import configparser, os
class inifile:
  def __init__(self, filename):
    self.filename = filename
    self.initflag = false
    self.cfg = none
    self.readhandle = none
    self.writehandle = none

  def init(self):
    self.cfg = configparser.configparser()
    try:
      self.readhandle = open(self.filename, 'r')
      self.cfg.readfp(self.readhandle)
      self.writehandle = open(self.filename, 'w')
      self.initflag = true
    except:
      self.initflag = false
    return self.initflag

  def uninit(self):
    if self.initflag:
      self.readhandle.close()
      self.writehandle.closse()

  def getvalue(self, section, key, default = ""):
    try:
      value = self.cfg.get(section, key)
    except:
      value = default
    return value

  def setvalue(self, section, key, value):
    try:
      self.cfg.set(section, key, value)
    except:
      self.cfg.add_section(section)
      self.cfg.set(section, key, value)
      self.cfg.write(self.writehandle)