python--工具--ini处理

python–工具–ini处理

# -*- coding: utf-8 -*-
"""
author:drliu
date:2022/3/18
desc: 该文件用于
sample:
获取INI配置文件内容
_config = parse_ini(_path)
使用现有的字典去修改INI
modify_ini(_file_path, _config_dict)
"""
# -----------------------------------------------------------------------------------------------------------
# 调用系统库,三方库
# -----------------------------------------------------------------------------------------------------------
import os
import sys
import re
import random
from ConfigParser import ConfigParser
from lib.print_log import print_log
from lib.global_args import *

# -----------------------------------------------------------------------------------------------------------
# 私有参数配置
# -----------------------------------------------------------------------------------------------------------
_current_file = os.path.abspath(__file__)
_current_dir = os.path.dirname(_current_file)


def replace_notes(file_path, old_list, new_list):
    """定义修改 # 号的函数,这么做的目的是为了使在使用ConfigParser的set时不把注释行去掉"""
    with open(file_path, 'r+') as fopen:
        w_str = ""
        for line in fopen:
            if re.search(old_list, line):
                # str(random.random()):随机的0-1的小数并转换为字符串
                line = re.sub(old_list, str(random.random()) + new_list, line)
                w_str += line
            else:
                w_str += line

    with open(file_path, 'w+') as wopen:
        wopen.write(w_str)


def recover_notes(file_path, old_list, new_list):
    """定义将 # 号修改回来的函数"""
    with open(file_path, 'r+') as fopen:
        w_str = ""
        for line in fopen:
            if re.search(old_list, line):
                line = re.sub(old_list, new_list, line)
                w_str += line
            else:
                w_str += line

    with open(file_path, 'w+') as wopen:
        wopen.write(w_str)


def modify_ini(file_path, config_dict):
    """
    modify target ini file based on input config_dict
    :param file_path:
    :param config_dict:
    :return:
    """
    try:
        if not os.path.exists(file_path):
            raise Exception('file:{0} not exists, please check '.format(file_path))

        # 修改带有#号的注释
        replace_notes(file_path, '#', '^.*aba11注释03aba = ')

        parser = ConfigParser()
        parser.read(file_path)

        if set(config_dict.keys()) > set(parser.sections()):
            raise Exception(
                'sections:{0} get from session memory not match file:{1} section :{2}'.format(config_dict.keys(), file_path,
                                                                                   parser.sections()))

        for section, section_values in config_dict.items():
            for key, value in section_values.items():
                parser.set(section, key, value)

        with open(file_path, "w+") as f:
            parser.write(f)

        # 将注释还原
        recover_notes(file_path, '^.*aba11注释03aba = ', '#', )

    except Exception as err:
        raise Exception(err)


def parse_ini(file_path):
    """
    :param file_path:
    :aim parse all key,sections in target ini
    :param file_name: /home/config/config.ini
    :return: {'INSIGHT': {'a': 'AA'}, 'GENERAL': {'time_interval': '30', 'target_path': '/home/yunwei', 'ommuser': 'zxomm', 'is_trust': '1'}}
    """
    try:
        if not os.path.exists(file_path):
            raise Exception('file:{0} not exists, please check '.format(file_path))

        parser = ConfigParser()
        parser.read(file_path)
        sections = parser.sections()
        _config = {}
        for item in sections:
            key_list = parser.options(item)
            _config[item] = {}
            for key in key_list:
                _config[item][key] = parser.get(item, key)

        return _config

    except Exception as err:
        raise Exception(err)


def main():
    """代码示例
    获取INI配置文件内容
    _config = parse_ini(_path)
    使用现有的字典去修改INI
    modify_ini(_file_path, _config_dict)
    """
    pass


if __name__ == '__main__':
    _config = parse_ini(TEST_CONFIG_FILE_PATH)
    print_log('INFO', _config)
    _config = {'common': {'test3': '37', }}
    modify_ini(TEST_CONFIG_FILE_PATH, _config)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值