zoukankan      html  css  js  c++  java
  • 解决openpyxl读取excel失败后,无法删除此excel的问题

    一、介绍

    在使用openpyxl读取已损坏的excel,此时你想删除此excel新建一个,但你会发现删除不掉,提示excel正在被另一个程序读取中。

    原因是当你的主线程用openpyxl读取excel失败时,它没有释放此读取资源,办法是用一个子线程去测试读取,如果有错误就让主线程去删除文件

    二、代码

    import gc
    import os
    import threading, traceback, sys
    from openpyxl import load_workbook, Workbook
    
    class runScriptThread(threading.Thread):  # The timer class is derived from the class threading.Thread
        def __init__(self, funcName, *args):
            threading.Thread.__init__(self)
            self.args = args
            self.funcName = funcName
            self.exitcode = 0
            self.exception = None
            self.exc_traceback = ''
    
        def run(self):  # Overwrite run() method, put what you want the thread do here
            try:
                self._run()
            except Exception as e:
                self.exitcode = 1  # 如果线程异常退出,将该标志位设置为1,正常退出为0
                self.exception = e
                self.exc_traceback = ''.join(traceback.format_exception(*sys.exc_info()))  # 在改成员变量中记录异常信息
    
        def _run(self):
            try:
                self.funcName(*(self.args))
            except Exception as e:
                raise e
    
    path=r"****************.xlsx"
    
    def read_openxl():
        wb = load_workbook(path,read_only=True)
    
    aChildThread = runScriptThread(read_openxl)
    aChildThread.start()
    aChildThread.join()
    
    if aChildThread.exitcode==1:
        del aChildThread
        gc.collect()
        os.remove(path)
        wb=Workbook()
        wb.save(path)
    
    else:
        wb = load_workbook(path,read_only=True)
        sheet_list=wb.get_sheet_names()
        print(sheet_list)
  • 相关阅读:
    IBinder在进程之间传递一个对象的形式(一)
    Xaml在string(串)定义常量和处理空间
    c 有意思的数组初始化
    C 文件直接包含
    [面试技巧]16个经典面试问题回答思路
    centos6安装bt工具transmission
    clearcase 中一些概念和操作
    C/C++ Resources
    Linux I/O 重定向详解及应用实例
    c/c++ 直接使用动态库 dlopen
  • 原文地址:https://www.cnblogs.com/angelyan/p/12425369.html
Copyright © 2011-2022 走看看