python 读写配置文件使用ConfigParser模块,该模块是python自带的读取配置文件的模块。通过他可以方便的读取配置文件,这里记录下简单的配置文件读写方法。
配置文件,顾名思议就是存放配置的文件。它包含三种元素:段名,关键字,值。有关配置文件的具体介绍可以参考百度百科。下 面是个简单的例子:
[info] resfile = BOOT.hex dstfile = APP.hex size = 1024
下面看一段读写配置文件的例子:
import ConfigParser config = ConfigParser.ConfigParser() with open("config.ini",'r+') as cfgfile: config.readfp(cfgfile) resFile = config.get("info","resFile") dstFile = config.get("info","dstFile") print "%s %s" % (resFile,dstFile) config.set("info","size","1024") config.write(open("config.ini", "w")) #write config size =config.get("info","size") print size cfgfile.close()
这段代码是怎样工作的呢?
首先导入这个ConfigParser模块,接着创建一个ConfigParser对象config。然后打开配置文件,文件对象名是cfgfile,并使用config对象的readfp()方法从cfgfile对象中读入数据。再使用get()方法获取关键字的值。使用set()方法设置新的关键字和值,并使用write()方法写入新的配置数据到文件。
ConfigParser 对象有如下一些方法:
1.读取配置文件
-read(filename) 直接读取ini文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型
2.写入配置文件
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置
需要调用write将内容写入配置文件。
参考文档:
http://docs.python.org/library/configparser.html
http://www.linux-field.com/?p=437