python

超轻量级php框架startmvc

python读写配置文件操作示例

更新时间:2020-07-10 22:06:01 作者:startmvc
本文实例讲述了python读写配置文件操作。分享给大家供大家参考,具体如下:在用编译型语

本文实例讲述了python读写配置文件操作。分享给大家供大家参考,具体如下:

在用编译型语言写程序的时候,很多时候用到配置文件,作为一个约定的规则,一般用 ini 文件作为配置文件,当然不是绝对的,也可能是XML等文件。

配置文件是配置的参数是在程序启动,或运行时需要的,作为编译型语言,几乎都会用到,但python是动态语言。动态语言的一大特性是解析执行的。所以很多情况下需要配置的参数,通常会被直接写在脚本里。一个常用的做法,就是单独用一个文件来作为配置文件,比如我们经常接触的 django ,他会用 settings.py ,urls.py 来配置一些参数。在需要修改的时候,直接修改这个 py 文件就可以了。

即使是这样,python 仍然提供了,读取配置文件的方法。在与其他系统结合的时候,通常会用得着。查看文档,自己实现了一个比较通用的读写配置文件的方法


# -*- coding:utf-8 -*-
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

在你的 py 脚本下你创建一个 inetMsgConfigure.ini 文件,然后进行测试就可以了。如果inetMsgConfigure.ini 这个文件根本不存在,你当然可以调用python  的方法,创建一个文件


file=open('inetMsgConfigure.ini','wb')
file.write(.........自由发挥)
file.close()

python 读写配置文件