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

相关文章

用django设置session过期时间的方法解析

session的超时时间设置 settings中 SESSION_COOKIE_AGE=60*30 30分钟。 SESSION_EXPIRE_AT_BROWSER_CLOSE...

python中zip()方法应用实例分析

本文实例分析了python中zip()方法的应用。分享给大家供大家参考,具体如下: 假设有一个集合set, 需要对set中的每个元素指定一个唯一的id,从而组建成一个dict结构。 这个...

django 控制页面跳转的例子

如下所示: def delEquipment(request, delip): print delip ip=delip conn= MySQLdb.connect(...

Django2.1集成xadmin管理后台所遇到的错误集锦(填坑)

Django2.1集成xadmin管理后台所遇到的错误集锦(填坑)

django默认是有一个admin的后台管理模块,但是丑,功能也不齐全,但是大神给我们已经集成好了xadmin后台,我们拿来用即可,但是呢,django已经升级到2.1版本了,xadmi...

python 读写文件包含多种编码格式的解决方式

今天写一个脚本文件,需要将多个文件中的内容汇总到一个txt文件中,由于多个文件有三种不同的编码方式,读写出现错误,先将解决方法记录如下: # -*- coding: utf-8 -*...