【问题标题】:How do I fix this error "The process cannot access the file because it is being used by another process"?如何解决此错误“该进程无法访问该文件,因为它正在被另一个进程使用”?
【发布时间】:2021-10-14 08:08:54
【问题描述】:

这是引发错误的代码的 sn-p:

writer=pd.ExcelWriter('C:\\Users\\aji/Curve.xlsx',engine='openpyxl')   
if os.path.exists('C:\\Users\\aji/Curve.xlsx'):
        os.remove('C:\\Users\\aji/Curve.xlsx')

我收到此错误消息:

PermissionError: [WinError 32] The process cannot access the file because it is being used by
another process: 'C:\\Users\\aji/Curve.xlsx'

我很确定路径中的文件没有打开。是什么导致了这个问题,我该如何解决?

【问题讨论】:

  • 什么是完整的回溯?另外,你在用 jupyter 吗?
  • 是的,我正在使用 jupyter。
  • 您可能运行了另一个打开该文件的单元格。重新启动内核并重试。另外,完成后请务必关闭编写器:writer.close()
  • 重启内核并在使用后关闭了写入器——但仍然出现错误。
  • 文件是否在excel中打开?

标签: python pandas windows error-handling file-permissions


【解决方案1】:

我认为您没有正确写入文件。结果,你的作者打开了文件。

根据the documentation

编写器应该用作上下文管理器。否则,调用close() 保存并关闭所有打开的文件句柄。

试试这个(假设你要写的DataFrame存储在df):

with pd.ExcelWriter('C:\\Users\\aji/Curve.xlsx', engine='openpyxl') as writer:
    df.to_excel(writer)

if os.path.exists('C:\\Users\\aji/Curve.xlsx'):
    os.remove('C:\\Users\\aji/Curve.xlsx')

我在上面提供的链接中还有其他很好的例子。我建议查看它们,以防另一个更适合您的用例。

正如评论者所建议的那样,混合斜线令人困惑。要么处处使用反斜杠,要么处处使用正斜杠。但这在技术上不应该引起问题,它只是分散注意力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多