zoukankan      html  css  js  c++  java
  • python配置文件操作——configparser模块

    # -*- coding: utf-8 -*-
    '''
    Version : Python27
    Author  : Spring God
    Date    : 2012-4-26
    Info    : 配置文件ini所在文件夹必需存在,否则抛出IOError异常,自处理之
    '''
    
    import sys
    
    if sys.hexversion >= 0x03000000:
        import configparser
    else:
        import ConfigParser as configparser
    
    
    def set_conf(ini_file, section, key, value):
    
        _config = configparser.ConfigParser()
    
        try:
            _config.read(ini_file)
            if not _config.has_section(section):
                _config.add_section(str(section))
            _config.set(str(section), str(key), str(value))
            with open(ini_file, 'w') as _file:
                _config.write(_file)
                _file.close()
                del _file
        finally:
            del _config
    
    
    def get_conf(ini_file, section, key):
    
        _config = configparser.ConfigParser()
    
        try:
            _config.read(ini_file)
            value = _config.get(str(section), str(key))
        except configparser.NoSectionError:
            value = None
        finally:
            del _config
    
        return value
    
    
    def del_conf(ini_file, section, key = None):
    
        _config = configparser.ConfigParser()
    
        try:
            _config.read(ini_file)
            if section != None and _config.has_section(section):
                if key != None:
                    _config.remove_option(section, key)
                else:
                    _config.remove_section(section)
                with open(ini_file, 'w') as _file:
                    _config.write(_file)
                    _file.close()
                    del _file
        finally:
            del _config
    
    
    if __name__ == '__main__':
    
        set_conf('set.ini', 'General', 'key', 'value')
        #print(get_conf('set.ini', 'General', 'key'))
        del_conf('set.ini', 'General', 'key')
  • 相关阅读:
    JQuery OOP 及 OOP思想的简易理解
    windows下编写shell脚本执行错误
    Kafka常用命令
    OffsetDateTime工具类
    windows下安装consul
    磁盘阵列方案
    shell基本语法记录
    学习CGLIB与JDK动态代理的区别
    Spring源码分析-BeanFactoryPostProcessors 应用之 PropertyPlaceholderConfigurer
    局域网内搭建git
  • 原文地址:https://www.cnblogs.com/doudongchun/p/3694812.html
Copyright © 2011-2022 走看看