Python 设置文件资源锁定

功能背景

        使用线程操作或者多个程序同时对同一个excel文件进行读写操作,不可避免的会操作冲突的问题,有没有一种方法就是可以不冲突,而是等待上一个程序使用完成后再对文件进行操作,就是等待一个完成再接着下一个?

实现方法

        使用线程锁,对资源进行控制

导入包

        import threading

初始化锁

        此处的锁一定是定义在函数外或使用的是global定义

        global_lock = threading.Lock()

获得锁

        global_lock.acquire()

释放锁

        global_lock.release()

整体代码

import traceback
import threading
import pandas as pd


global_lock = threading.Lock()

def write_to_excel(file_path, info_dict):
    """
    以df写入的字典的形式,追加写入文件中
    :param file_path: 文件路径
    :param info_dict: 需要写入的信息字典
    :return: 
    """
    try:
        global_lock.acquire()
        if not os.path.exists(file_path):
            df = pd.DataFrame()
            df.to_excel(file_path, index=False)
        df = pd.read_excel(file_path)
        df = df._append(info_dict, ignore_index=True)
        df["商品ID"] = df["商品ID"].astype(str)
        df.to_excel(file_path, index=False)

    except Exception as e:
        print(traceback.format_exc())
    finally:
        global_lock.release()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值