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 的枚举 Enum

枚举是常用的功能,看看Python的枚举. from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'A...

Python matplotlib以日期为x轴作图代码实例

Python matplotlib以日期为x轴作图代码实例

这篇文章主要介绍了Python matplotlib以日期为x轴作图代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 效果图如下...

Python实现图片转字符画的示例代码

Python实现图片转字符画的示例代码

初学Python,在网上看到Python图片转字符画的教程,我也来尝试下。 首先我们要用到Python的PIL库的Image模块,PIL(Python Imaging Library...

pandas 数据实现行间计算的方法

如下所示: ###方法1:用shift函数,不用通过循环 import pandas as pd import numpy as np import matplotlib as p...

Python Web框架Pylons中使用MongoDB的例子

Pylons 经过漫长的开发,终于放出了 1.0 版本。对于正规的产品开发来说,1.0 版本的意义很大,这表明 Pylons 的 API 终于稳定下来了。 Pylons 虽是山寨 Rai...