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

相关文章

解决Mac下使用python的坑

操作系统:macOS High Sierra 10.13.3 Python3.6 因为此版本自带python2.7,就下载并安装了anaconda2的版本,结果使用的时候系统自带的pyt...

Python中非常实用的一些功能和函数分享

在使用Python多年以后,我偶然发现了一些我们过去不知道的功能和特性。一些可以说是非常有用,但却没有充分利用。考虑到这一点,我编辑了一些你应该了解的Python功能特色。 带任意数量参...

django 修改server端口号的方法

django 修改server端口号的方法

django可以在运行服务器时指定端口号 python manage.py runserver 8080 我们启动django开发服务器,输入命令 manage.py runser...

web.py 十分钟创建简易博客实现代码

一、web.py简介 web.py是一款轻量级的Python web开发框架,简单、高效、学习成本低,特别适合作为python web开发的入门框架。官方站点:http://webpy....

详解Python中映射类型(字典)操作符的概念和使用

映射类型操作符 (1)标准类型操作符         字典可以和所有的标准类型操作符一起工作,但却不支持像拼接(co...