POP Article V2.0 设为主页
收藏本站
首 页交流论坛留 言
您现在的位置:首 页 >> Python 与 XML >> Python开发 >> 查看文章
Python之简洁ini读写
作者:tamsyn  来源:www.sqlite.com.cn  时间:2008-6-4  【 字体: 】 〖 双击滚屏 〗

ini文件是常用的配置文件格式,当然,除了它之外,还有其他好多种,比如confxml等等。不过,今天就谈论ini罢了。

python对此提供了相应的模块,示例如下:

#coding=utf-8
import ConfigParser
def writeConfig(filename):
        config = ConfigParser.ConfigParser()
        # set db
        section_name = 'db'
        config.add_section( section_name  )
        config.set( section_name, 'dbname', 'MySQL')
        config.set( section_name, 'host', '127.0.0.1')
        config.set( section_name, 'port', '80')
        config.set( section_name, 'password', '123456')
        config.set( section_name, 'databasename', 'test')
        # set app
        section_name = 'app'
        config.add_section( section_name  )
        config.set( section_name, 'loggerapp', '192.168.20.2')
        config.set( section_name, 'reportapp', '192.168.20.3')
        # write to file
        config.write( open(filename, 'a') )
        
def updateConfig(filename, section, **keyv):
        config = ConfigParser.ConfigParser()
        config.read(filename)
        [config.set(section, key, keyv[key]) for key in keyv if config.has_option(section, key)]
        config.write( open(filename, 'r+') )
        
if __name__ == '__main__':
        file_name = 'test.ini'
        writeConfig(file_name)
        updateConfig(file_name, 'app', reportapp = '192.168.100.100')
        print "end__"
浏览次数:   【 打 印 】【 关 闭
上一篇:python操作注册表两例
下一篇:TPL正则表达式
 论坛登陆
用户名:
密  码:
验证码: 
Cookie 选项:
正常登陆 隐身登陆
   
没有注册?
 文章搜索
 推荐文章
 酷站推荐
 热门文章
 网站统计
关于我们 | 网站地图 | 联系我们 | 网站历史 | 友情链接 | TOP
Copyright© 2006 Sqlite中文社区  程序开发: mistletoe  站长: 林轩 陈文成