首页 > 解决方案 > WinError 32 进程无法访问文件,因为它正在被另一个进程使用,无法通过python或手动删除文件

问题描述

大家好,我有一个程序可以创建并保存一个 xlsx 文件,然后打开它并转换为 pdf ......但是我希望它删除原始的 xlsx 文件。

  1. 它在正确的目录中创建这两个文件。
  2. 但是它不会删除 xlsx,我也不能手动删除它,因为它说文件仍然打开
        wb.save(NEW_RECEIPT_PATH + new_file_name_xlsx)


        #this should turn the xlsx into a pdf
        xlApp = client.Dispatch("Excel.Application")
        books = xlApp.Workbooks.Open(NEW_RECEIPT_PATH + new_file_name_xlsx)
        ws2 = books.Worksheets[0]
        ws2.Visible = 1
        save_the_pdf = NEW_RECEIPT_PATH + new_file_name_pdf
        ws2.ExportAsFixedFormat(0,save_the_pdf)

        #this removes the xlsx file
        os.remove(NEW_RECEIPT_PATH + new_file_name_xlsx)

我的预感是我没有在正确的地方使用 .close() 并且它只是打开了 excel 文件。我努力了...

        wb.save(NEW_RECEIPT_PATH + new_file_name_xlsx)
        wb.close()


        #this should turn the xlsx into a pdf
        xlApp = client.Dispatch("Excel.Application")
        books = xlApp.Workbooks.Open(NEW_RECEIPT_PATH + new_file_name_xlsx)
        ws2 = books.Worksheets[0]
        ws2.Visible = 1
        save_the_pdf = NEW_RECEIPT_PATH + new_file_name_pdf
        ws2.ExportAsFixedFormat(0,save_the_pdf)


        #this removes the xlsx file
        os.remove(NEW_RECEIPT_PATH + new_file_name_xlsx)

无济于事。任何线索将不胜感激。

-更新-

我已经确定问题出在这些方面......

#this should turn the xlsx into a pdf
        xlApp = client.Dispatch("Excel.Application")
        books = xlApp.Workbooks.Open(NEW_RECEIPT_PATH + new_file_name_xlsx)
        ws2 = books.Worksheets[0]
        ws2.Visible = 1
        save_the_pdf = NEW_RECEIPT_PATH + new_file_name_pdf
        ws2.ExportAsFixedFormat(0,save_the_pdf)

xlsx 文件保持打开状态,不会让我通过代码将其删除...与手动删除 xlsx 文件相同。我必须双击文件打开它,然后关闭它才能删除。

如何在此代码末尾关闭 xlsx 文件?

标签: pythonopenpyxl

解决方案


放心,伙计们……因为我以为我没有正确关闭它。下面的代码效果很好。

该死的,我讨厌被困几天。

#this should turn the xlsx into a pdf
        xlApp = client.Dispatch("Excel.Application")
        books = xlApp.Workbooks.Open(NEW_RECEIPT_PATH + new_file_name_xlsx)
        ws2 = books.Worksheets[0]
        ws2.Visible = 1
        save_the_pdf = NEW_RECEIPT_PATH + new_file_name_pdf
        ws2.ExportAsFixedFormat(0,save_the_pdf)
        books.Close(True) # save the workbook

        #this removes the xlsx file
        os.remove(NEW_RECEIPT_PATH + new_file_name_xlsx)

推荐阅读