# -*- 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')