python - WinError 32 进程无法访问文件,因为它正在被另一个进程使用,无法通过python或手动删除文件
问题描述
大家好,我有一个程序可以创建并保存一个 xlsx 文件,然后打开它并转换为 pdf ......但是我希望它删除原始的 xlsx 文件。
- 它在正确的目录中创建这两个文件。
- 但是它不会删除 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 文件?
解决方案
放心,伙计们……因为我以为我没有正确关闭它。下面的代码效果很好。
该死的,我讨厌被困几天。
#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)
推荐阅读
- react-native - 在 CRNA 项目中添加非 JS(转译)文件
- cors - OPENTOK REST API 不起作用
- java - org.jboss.classfilewriter.DuplicateMemberException
- java - 使用 selenium/java 生成随机字符并发送到文本字段
- pandas - Pandas Dataframe 根据算术距离有条件地更改值
- c# - 始终表示数据库状态的只读 POCO
- export-to-csv - 使用海龟坐标导出世界
- c# - 如何在标签中显示计时器的剩余时间?
- java - Spring Boot 中的多播 Websocket
- c# - 如何使用 NUnit 在 .NET Core 中模拟 UserManager?