WinError 32进程无法访问该文件,因为另一个进程正在使用该文件无法通过python或手动删除文件

问题描述 投票:-1回答:1

大家好我有一个程序,它创建并保存一个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)

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

-update-

我已经确定了这些问题......

#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文件?

python openpyxl
1个回答
0
投票

放心......我以为我没有正确关闭它。下面的代码非常出色。

该死,我讨厌被困几天。

#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)
© www.soinside.com 2019 - 2024. All rights reserved.