首页 > 编程 > Python > 正文

python读写配置文件操作示例

2019-11-25 12:32:23
字体:
来源:转载
供稿:网友

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

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

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

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

# -*- coding:utf-8 -*-import ConfigParserimport osclass 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相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表