【问题标题】:PermissionError [WinError 32]: File is being used by another process after opening excel file with xlwingsPermissionError [WinError 32]:使用 xlwings 打开 excel 文件后,文件正被另一个进程使用
【发布时间】: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 上出现但在 Mac 上不出现的原因是什么?
  • 是否有更好/不同的方法来触发 Excel 中的公式计算,而无需通过应用程序打开工作簿,这可能是导致此问题的原因

【问题讨论】:

    标签: python windows xlwings


    【解决方案1】:

    macOS 不会仅仅因为文件正被其他应用程序使用而阻止文件,因此即使您删除可能仍在应用程序中打开的文件,您也不会收到错误消息。

    另一方面,Windows 不允许您在文件或文件夹在某处打开后立即删除它。

    现在,在您的情况下,Python 想要删除文件,而 Excel 仍在关闭文件的过程中,这就是您收到错误的原因。

    上次我遇到这个问题时,我是这样解决的:

    import time
    
    for attempt in range(5):
        try:
            temp_path.unlink()
            break
        # you may want to explicitly check for PermissionError
        except Exception as e:
            time.sleep(1)
    
    

    关于您的最后一个问题:我不知道任何 Python 库可以在没有 Excel 的情况下评估公式,但我相信其他语言(例如 C#)存在此类库。

    【讨论】:

      猜你喜欢
      • 2022-07-27
      • 2023-01-14
      • 2015-11-13
      • 2015-01-28
      • 1970-01-01
      • 2017-06-02
      • 2021-09-21
      • 2019-11-26
      • 2022-11-14
      相关资源
      最近更新 更多