python读写配置文件操作示例

作者:轻舞肥羊 时间:2021-12-12 03:51:29 

本文实例讲述了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程序设计有所帮助。

来源:http://www.yihaomen.com/article/python/253.htm

标签:python,读写配置文件
0
投稿

猜你喜欢

  • PHP函数篇详解十进制、二进制、八进制和十六进制转换函数说明

    2023-11-24 06:26:11
  • Javascirpt打造“互动指针”特效

    2013-08-06 07:37:52
  • python多进程下的生产者和消费者模型

    2022-05-30 02:37:07
  • ASP图片分页代码 (通用)

    2009-06-22 12:57:00
  • Mango Cache缓存管理库TinyLFU源码解析

    2023-09-02 12:27:51
  • 设计工作者必须了解的常识

    2008-04-06 13:56:00
  • 增强网站的魅力 网页制作技巧三则

    2007-10-04 10:06:00
  • Python利用Redis计算经纬度距离案例

    2021-03-05 04:51:35
  • 针对google Chrome的 CSS hacks

    2009-11-30 12:45:00
  • 用Popup窗口建无限级Web页菜单

    2023-07-10 20:22:17
  • java-jsp springmvc-controller 传值到页面的方法

    2023-06-16 18:19:52
  • ASP编程入门进阶(十四):Browser & Linkin

    2008-06-12 07:08:00
  • javascript中的关于类型转换的性能优化

    2023-06-26 16:25:48
  • PHP取余函数介绍MOD(x,y)与x%y

    2023-10-02 20:15:55
  • Python实现CET查分的方法

    2023-06-13 12:05:51
  • 淘宝CSS框架研究(1):Reset CSS(八卦篇)

    2009-03-31 12:58:00
  • 使用Filter实现信息的二次检索

    2007-10-08 19:19:00
  • IE bug: 1像素的dotted/dashed边框

    2009-10-28 18:45:00
  • 如何在2003系统注册fso组件

    2010-11-29 19:55:00
  • PHP+JS实现文件分块上传的示例代码

    2023-06-12 00:04:07
  • asp之家 网络编程 m.aspxhome.com