脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python读写配置文件操作示例

python读写配置文件操作示例

2021-07-30 00:45轻舞肥羊 Python

这篇文章主要介绍了python读写配置文件操作,结合实例形式分析了Python针对ini配置文件的读取、解析、写入等相关操作技巧,需要的朋友可以参考下

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

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# -*- 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  的方法,创建一个文件

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

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

原文链接:http://www.yihaomen.com/article/python/253.htm

延伸 · 阅读

精彩推荐