您的位置:首页 > 编程语言 > Python开发

python配置文件操作

2015-03-08 14:37 267 查看
python 读写配置文件 ConfigParser模块是python自带的读取配置文件的模块,借助它可以方便的读取配置文件。配置文件,顾名思议就是存放配置的文件。

python 读写配置文件

ConfigParser模块是python自带的读取配置文件的模块,借助它可以方便的读取配置文件。

配置文件,顾名思议就是存放配置的文件。

例:



复制代码代码如下:

[info]

age = 21

name = chen

gender = male



其中[ ] 中的info是这段配置的名字下面age,name都是属性下面的代码演示了如何读取python 读写配置文件和修改配置中变量的值:



复制代码代码如下:

from __future__ import with_statement

import ConfigParser

config=ConfigParser.ConfigParser()

with open(''testcfg.cfg'',''rw'') as cfgfile:

config.readfp(cfgfile)

name=config.get(''info'',''name'')

age=config.get(''info'',''age'')

print name

print age

config.set(''info'',''gender'',''male'')

config.set(''info'',''age'',''21'')

age=config.get(''info'',''age'')

print name

print age

首先,config=ConfigParser.ConfigParser()得到一个配置config对象.下面打开一个配置文件 cfgfile. 用readfp()读取这个文件.这样配置的内容就读到config对象里面了。

如何读取值,常用的方法是get() 和getint() . get()返回文本. getint()返回整数:

name=config.get(''info'',''name'')

说明:

读取config中info段中的name变量值.最后讲讲如何设置值.使用set(段名,变量名,值) 来设置变量.config.set(''info'',''age'',''21'') 表示把info段中age变量设置为21。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: