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操作mysql数据库(cursor游标讲解)

带你彻底搞懂python操作mysql数据库(cursor游标讲解)

1、什么是游标? 一张图讲述游标的功能: 图示说明: 2、使用游标的好处? 如果不使用游标功能,直接使用select查询,会一次性将结果集打印到屏幕上,你无法针对结果集做第二次编...

Python封装shell命令实例分析

本文实例讲述了Python封装shell命令的方法。分享给大家供大家参考。具体实现方法如下: # -*- coding: utf-8 -*- import os import sub...

在Python的Django框架中获取单个对象数据的简单方法

相对列表来说,有些时候我们更需要获取单个的对象, `` get()`` 方法就是在此时使用的: >>> Publisher.objects.get(name="Ap...

Python地图绘制实操详解

Python地图绘制实操详解

网上有很多地图绘制的教程,更多趋向于全国地图或者省级地图,但有时我们需要到县级。闲得慌,今天以贵州省毕节市为例,分享一篇Python县级地图的绘制(遥想当时差点把百度翻了个底朝天),希望...

Python+OpenCV+图片旋转并用原底色填充新四角的例子

我就废话不多说了,直接上代码吧! import cv2 from math import fabs, sin, cos, radians import numpy as np fro...