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')
  • 相关阅读:
    541. Reverse String II
    540. Single Element in a Sorted Array
    初识python
    openCV
    openCV
    win环境下安装配置openCV-4.3.0
    力扣Leetcode 198. 打家劫舍
    力扣Leetcode 680. 验证回文字符串 Ⅱ
    力扣Leetcode 560. 和为K的子数组
    华师2019软件专硕复试机试题最后一题G:找数
  • 原文地址:https://www.cnblogs.com/doudongchun/p/3694812.html
Copyright © 2011-2022 走看看