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程序设计有所帮助。

相关文章

matplotlib实现显示伪彩色图像及色度条

matplotlib实现显示伪彩色图像及色度条

灰度图显示为伪彩色图 法一 import matplotlib.pyplot as plt img = plt.imread('C:/Users/leex/Desktop/lena...

使用beaker让Facebook的Bottle框架支持session功能

bottle是一个小型web框架,很小只有一个文件,但功能确很强大,学起来也简单,简单和小巧的同时也有很多不足,某些功能支持还不是很完善,比如session.但是也有它自身的好处,我们可...

Python应用领域和就业形势分析总结

Python应用领域和就业形势分析总结

简单的说,Python是一个“优雅”、“明确”、“简单”的编程语言。 学习曲线低,非专业人士也能上手 开源系统,拥有强大的生态圈 解释型语言,完美的平台可移植性 支持面...

几个提升Python运行效率的方法之间的对比

几个提升Python运行效率的方法之间的对比

在我看来,python社区分为了三个流派,分别是python 2.x组织,3.x组织和PyPy组织。这个分类基本上可以归根于类库的兼容性和速度。这篇文章将聚焦于一些通用代码的优化技巧以及...

Python+Selenium+PIL+Tesseract自动识别验证码进行一键登录

Python+Selenium+PIL+Tesseract自动识别验证码进行一键登录

本文介绍了Python+Selenium+PIL+Tesseract自动识别验证码进行一键登录,分享给大家,具体如下: Python 2.7 IDE Pycharm 5.0.3...