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

yipeiwu_com6年前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循环中else,break和continue的用法实例详解

本文实例讲述了Python循环中else,break和continue的用法。分享给大家供大家参考,具体如下: 在看Python的文档的时候看到了for和while语句和C语言中有一个最...

Python中PyQt5/PySide2的按钮控件使用实例

Python中PyQt5/PySide2的按钮控件使用实例

在之前的文章中,我们介绍了PyQt5和PySide2中主窗口控件MainWindow的使用、窗口控件的4中基础布局管理。从本篇开始,我们来了解一下PyQt5和PySide2中基础控件的使...

Python3实现将文件树中所有文件和子目录归档到tar压缩文件的方法

本文实例讲述了Python3实现将文件树中所有文件和子目录归档到tar压缩文件的方法。分享给大家供大家参考。具体实现方法如下: # 这里将一个文件树中的所有文件和子目录归档到一个ta...

详解python中Numpy的属性与创建矩阵

ndarray.ndim:维度 ndarray.shape:形状 ndarray.size:元素个数 ndarray.dtype:元素数据类型 ndarray.itemsize:字节大小...

django框架使用orm实现批量更新数据的方法

本文实例讲述了django框架使用orm实现批量更新数据的方法。分享给大家供大家参考,具体如下: 好久没有用django来改版博客了,突然感觉到生疏了。没办法,业余玩python,dja...