zoukankan      html  css  js  c++  java
  • ConfigParser 读写配置文件

    很多时候需要从配置文件中读取参数,在程序中使用,这时候就需要用到ConfigParser模块(在Python3以上的版本中为configparser模块)
    首先新建一个配置文件样例:myapp.conf

    # database source
    [db]
    host = 127.0.0.1
    port = 3306
    user = root
    pass = root
    # ssh
    [ssh]
    host = 192.168.1.101
    user = huey
    pass = huey
    

    在Python代码中:

    #实例化 ConfigParser 并加载配置文件
    cp = ConfigParser.SafeConfigParser()
    cp.read('myapp.conf')
    
    #获取 section 列表、option 键列表和 option 键值元组列表 
    print 'all sections:', cp.sections()        # sections: ['db', 'ssh']
    print 'options of [db]:', cp.options('db')  # options of [db]: ['host', 'port', 'user', 'pass']
    print 'items of [ssh]:', cp.items('ssh')    # items of [ssh]: [('host', '192.168.1.101'), ('user', 'huey'), ('pass', 'huey')]
    
    #读取指定的配置信息
    print 'host of db:', cp.get('db', 'host')     # host of db: 127.0.0.1
    print 'host of ssh:', cp.get('ssh', 'host')   # host of ssh: 192.168.1.101
    
    #按类型读取配置信息:getint、 getfloat 和 getboolean
    print type(cp.getint('db', 'port'))        # <type 'int'>
    
    #判断 option 是否存在
    print cp.has_option('db', 'host')    # True
    
    #设置 option
    cp.set('db', 'host','192.168.1.102')
    
    #删除 option
    cp.remove_option('db', 'host')
    
    #判断 section 是否存在
    print cp.has_section('db')    # True
    
    #添加 section
    cp.add_section('new_sect')
    
    #删除 section
    cp.remove_section('db')
    
    #保存配置,set、 remove_option、 add_section 和 remove_section 等操作并不会修改配置文件,write 方法可以将 ConfigParser 对象的配置写到文件中
    cp.write(open('myapp.conf', 'w'))
    cp.write(sys.stdout)
    
    

    如果配置文件中有中文等字符,可以使用codecs读取文件

    import ConfigParser
    import codecs
    
    cp = ConfigParser.SafeConfigParser()
    with codecs.open('myapp.conf', 'r', encoding='utf-8') as f:
        cp.readfp(f)
    
    

    DEFAULT section

    [DEFAULT]
    host = 127.0.0.1
    port = 3306
    
    [db_root]
    user = root
    pass = root
    
    [db_huey]
    host = 192.168.1.101
    user = huey
    pass = huey
    -------------------------
    print cp.get('db_root', 'host')    # 127.0.0.1
    print cp.get('db_huey', 'host')    # 192.168.1.101
    

    存在的问题:
    ConfigParser的一些问题:

    • 不能区分大小写。
    • 重新写入的配置文件不能保留原有配置文件的注释。
    • 重新写入的配置文件不能保持原有的顺序。
    • 不支持嵌套。
    • 不支持格式校验。

    易用性
    综合上述ConfigParse的一些问题,如果在使用时,不需要写回, 还是ConfigParser 更易用一些, 只要注意配置文件的参数尽量使用小写即可; 否则, 建议使用configobj。
    注意事项
    配置参数读出来都是字符串类型, 参数运算时,注意类型转换,另外,对于字符型参数,不需要加引号

  • 相关阅读:
    我已经发表的文章:2,《上帝的小蚂蚁》(未经作者本人同意,不得转载!)
    【windows环境下】RabbitMq的安装和监控插件安装
    Apache FtpServer扩展【动手实现自己的业务】
    我的博客开始之旅
    curl和wget的区别和使用 wanglf
    ceph集群部署 wanglf
    ansible实现SSH配置免密互信 wanglf
    kubernetes(k8s) helm安装kafka、zookeeper wanglf
    django项目中使用KindEditor富文本编辑器 wanglf
    下一代网页:当HTML5取代Flash
  • 原文地址:https://www.cnblogs.com/sandy-t/p/9761497.html
Copyright © 2011-2022 走看看