解決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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM