configparser库_ini配置文件处理记录_240907

configparser库是Python的一个内置库,用于处理配置文件。它提供了一个类似于字典的接口,可以方便地读取和写入INI格式的配置文件。

def token_reset():
    # 初始化根据ini配置文件批量获取TOKEN
    config = configparser.ConfigParser()
    config.read(TOKEN_INI, encoding='utf-8-sig')  # 指定编码为utf-8-sig
    
    for section in config:  
        if section != 'DEFAULT':      
            data = dict(config.items(section))
            get_token(section,data)
    logger.debug(f"************批量获取Token完成************")
    return 0
def read_config(filename, section):
    # 根据运营商名称获取transid
    try:
        # 创建一个ConfigParser对象
        config = configparser.ConfigParser()
        # 读取配置文件,指定编码为utf-8-sig
        config.read(filename, encoding='utf-8-sig')
        # 检查指定的section是否存在于配置文件中
        if section in config:
            # 获取section下的所有键值对,并将其转换为字典
            transid = dict(config.items(section))
            return transid
        else:
            # 如果section不存在,记录错误日志并返回1
            logger.error(f"{filename}没找到:{section}")
            return 1
    except Exception as e:
        # 如果发生异常,记录错误日志并返回1
        logger.error(f"{filename}没找到:{section}-{e}")
        return 1
def update_tokenini_data(section, key, value):
    # 使用锁确保线程安全
    with ini_lock:
        try:
            # 创建一个ConfigParser对象
            config = configparser.ConfigParser()
            # 读取配置文件
            config.read(TOKEN_RSP)
            # 如果配置文件中不存在指定的section,则添加该section
            if not config.has_section(section):
                config.add_section(section)
            # 设置指定section下的key-value对
            config.set(section, key, value)
            # 将修改后的配置写回文件
            with open(TOKEN_RSP, 'w') as configfile:
                config.write(configfile)
        except Exception as e:
            # 记录错误日志
            logger.error(f"{e}")
            # 如果配置文件中存在指定的section,尝试删除并重新添加
            if config.has_section(section):
                try:
                    config.remove_section(section)
                    config.add_section(section)
                    config.set(section, key, value)
                    with open(TOKEN_RSP, 'w') as configfile:
                        config.write(configfile)
                except Exception as e2:
                    # 记录错误日志
                    logger.error(f"Failed to replace section and key-value pair: {e2}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值