【发布时间】:2021-05-07 22:16:37
【问题描述】:
说明
为了触发 excel 中某些公式字段的计算,然后使用 pandas 读取它们的值,我有以下脚本部分,它在 excel 中打开工作簿,然后保存并关闭工作簿并尝试删除打开工作簿时创建的临时文件:
def df_from_excel(path):
"""Automates the opening and saving of an excel workbook before reading it
in through pd.read_excel, which addresses the NaN issue described in this
post: https://stackoverflow.com/a/41730454/7338319
"""
# open and save the wb to trigger formulas
app = xl.App(visible=False)
book = app.books.open(path)
book.save()
book.close()
app.kill()
# delete the temporary file that's created
temp_path = path.parent / ("~$" + str(path.name))
if temp_path.exists():
temp_path.unlink()
# read the excel into a dataframe
return pd.read_excel(path, engine="openpyxl")
此脚本在 Mac 上成功运行,但当我尝试在 Windows 上运行时,出现以下错误,这似乎是由 temp_path.unlink() 引发的
self = WindowsPath('C:/Users/william.daly/Documents/GitHub/prompt_payment/tests/run/~$CoreIntegrator.xlsx')
def unlink(self):
"""
Remove this file or link.
If the path is a directory, use rmdir() instead.
"""
if self._closed:
self._raise_closed()
> self._accessor.unlink(self)
E PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\william.daly\\Documents\\GitHub\\prompt_payment\\tests\\run\\~$CoreIntegrator.xlsx'
env\lib\pathlib.py:1304: PermissionError
附加上下文
- 我正在尝试使用 Windows Server 2019 Standard 在虚拟桌面上运行此脚本
- 我正在使用 python 3.7.7 和 xlwings 版本 0.21.4
- 我试图执行的脚本部分主要来自这个答案:https://stackoverflow.com/a/41730454/7338319
- 我根据本期的注释添加了
book.close():PermissionError: [WinError 32] The process cannot access the file because it is being used by another process - 我也不能再手动删除文件了,大概是因为同样的问题
问题
- 是否有更好/不同的方法来强制关闭文件?
- 此错误在 Windows 上出现但在 Mac 上不出现的原因是什么?
- 是否有更好/不同的方法来触发 Excel 中的公式计算,而无需通过应用程序打开工作簿,这可能是导致此问题的原因
【问题讨论】: