六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 45|回复: 0

python 的配置文件模块

[复制链接]

升级  8.67%

68

主题

68

主题

68

主题

举人

Rank: 3Rank: 3

积分
226
 楼主| 发表于 2013-1-15 02:55:59 | 显示全部楼层 |阅读模式
 
写入配置文件:
import ConfigParser, os #引用的模块:config = ConfigParser.RawConfigParser()# When adding sections or items, add them in the reverse order of# how you want them to be displayed in the actual file.# In addition, please note that using RawConfigParser's and the raw# mode of ConfigParser's respective set functions, you can assign# non-string values to keys internally, but will receive an error# when attempting to write to a file or when you get it in non-raw# mode. SafeConfigParser does not allow such assignments to take place.config.add_section('Section1')config.set('Section1', 'int', '15')config.set('Section1', 'bool', 'true')config.set('Section1', 'float', '3.1415')config.set('Section1', 'baz', 'fun')config.set('Section1', 'bar', 'Python')config.set('Section1', 'foo', '%(bar)s is %(baz)s!')# Writing our configuration file to 'example.cfg'with open('example.cfg', 'wb') as configfile:    config.write(configfile)

读入这个配置文件:
import ConfigParserconfig = ConfigParser.RawConfigParser()config.read('example.cfg')# getfloat() raises an exception if the value is not a float# getint() and getboolean() also do this for their respective typesfloat = config.getfloat('Section1', 'float')int = config.getint('Section1', 'int')print float + int# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.# This is because we are using a RawConfigParser().if config.getboolean('Section1', 'bool'):    print config.get('Section1', 'foo')
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表