python读写ini配置文件方法实例分析

yipeiwu_com5年前Python基础

本文实例讲述了python读写ini配置文件方法。分享给大家供大家参考。具体实现方法如下:

import ConfigParser
import os
class ReadWriteConfFile:
  currentDir=os.path.dirname(__file__) 
  filepath=currentDir+os.path.sep+"inetMsgConfigure.ini"
  @staticmethod
  def getConfigParser():
    cf=ConfigParser.ConfigParser()
    cf.read(ReadWriteConfFile.filepath)
    return cf
  @staticmethod
  def writeConfigParser(cf):
    f=open(ReadWriteConfFile.filepath,"w");      
    cf.write(f)
    f.close();
  @staticmethod
  def getSectionValue(section,key):
    cf=ReadWriteConfFile.getConfigParser()
    return cf.get(section, key)
  @staticmethod
  def addSection(section):
    cf=ReadWriteConfFile.getConfigParser()
    allSections=cf.sections()
    if section in allSections:
      return
    else:
      cf.add_section(section)
      ReadWriteConfFile.writeConfigParser(cf)
  @staticmethod
  def setSectionValue(section,key,value):
    cf=ReadWriteConfFile.getConfigParser()
    cf.set(section, key, value)
    ReadWriteConfFile.writeConfigParser(cf)
if __name__ == '__main__':
  ReadWriteConfFile.addSection( 'messages')
  ReadWriteConfFile.setSectionValue( 'messages','name','sophia')
  x=ReadWriteConfFile.getSectionValue( 'messages','1000')
  print x

希望本文所述对大家的Python程序设计有所帮助。

相关文章

在Python web中实现验证码图片代码分享

在Python web中实现验证码图片代码分享

系统版本: CentOS 7.4 Python版本: Python 3.6.1 在现在的WEB中,为了防止爬虫类程序提交表单,图片验证码是最常见也是最简单的应对方法之一。 1.验证码图...

使用Python-OpenCV向图片添加噪声的实现(高斯噪声、椒盐噪声)

在matlab中,存在执行直接得函数来添加高斯噪声和椒盐噪声。Python-OpenCV中虽然不存在直接得函数,但是很容易使用相关的函数来实现。 代码: import numpy a...

python如何拆分含有多种分隔符的字符串

案例:        把某个字符串依据分隔符拆分,该字符包含不同的多种分隔符,如下    &nb...

深入理解python中的atexit模块

atexit 模块介绍 python atexit 模块定义了一个 register 函数,用于在 python 解释器中注册一个退出函数,这个函数在解释器正常终止时自动执行,一般用来...

python实现守护进程、守护线程、守护非守护并行

守护进程 1、守护子进程 主进程创建守护进程 其一:守护进程会在主进程代码执行结束后就终止 其二:守护进程内无法再开启子进程,否则抛出异常:AssertionError:...