【问题标题】:os.remove - PermissionError: [WinError 32] The process cannot access the file because it is being used by another processos.remove - PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用
【发布时间】:2021-09-21 10:26:36
【问题描述】:

[Python] 我在其他帖子中尝试了很多建议,但无法解决 PermissionError: [WinError 32] The process cannot access the file because it is being used by another process

import os
from shutil import copyfile


LogFile = 'CCH Prepare Delta.txt'

if os.path.exists(LogFile):
    lastmod = datetime.datetime.fromtimestamp(os.path.getmtime(LogFile)).strftime('%Y-%m-%d %H-%M-%S')
    copyfile(LogFile, 'Log/'+LogFile.replace('.txt',' '+lastmod+'.txt'))
    os.remove(LogFile)

完整的错误信息是:

---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
<ipython-input-43-cb0f2cf501af> in <module>
      8     lastmod = datetime.datetime.fromtimestamp(os.path.getmtime(LogFile)).strftime('%Y-%m-%d %H-%M-%S')
      9     copyfile(LogFile, 'Log/'+LogFile.replace('.txt',' '+lastmod+'.txt'))
---> 10     os.remove(LogFile)

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'CCH Prepare Delta.txt'

据我所知,使用copyfile后,文件会自行关闭?以前我在 os.rename 上也遇到了同样的问题。我在 Microsoft 资源监视器中找到了一种手动方法,它是结束进程,但它似乎不是动态的。想在代码本身中找到解决方案。

非常感谢您提前提供的帮助!

【问题讨论】:

  • 结束什么进程?其他一些程序认为该文件很重要,不希望您删除它。
  • 您可以查看此答案以找出正在使用您的文本文件的进程:stackoverflow.com/a/39637414/4644059,然后终止它。但终止听起来不是一种安全的方法。

标签: python


【解决方案1】:

其他进程打开了您的文件,您必须先强制​​其他进程关闭文件,方法是杀死它或通过其他方式。更多信息在这里:

How can I delete a file that is in use by another process?

【讨论】:

  • 要让它运行,我必须杀死'python.exe'。 Jupyter Notebook 也停止并需要重新启动。有没有其他办法?
  • 嗯,你可以强制进程关闭日志文件而不杀死它。
【解决方案2】:

到目前为止,我只发现了一种解决方案,但对我来说似乎并不好,即:

if os.path.exists(LogFile):
    lastmod = datetime.datetime.fromtimestamp(os.path.getmtime(LogFile)).strftime('%Y-%m-%d %H-%M-%S')
    copyfile(LogFile, 'Log/'+LogFile.replace('.txt',' '+lastmod+'.txt'))
    try:
        os.remove(LogFile)
    except: #PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
        for proc in psutil.process_iter():
            if proc.name() == 'python.exe':
                proc.kill()
        os.remove(LogFile)

问题是,在这一步之后,内核(Jupyter Notebook)必须重新启动并从头开始运行。希望任何人都可以提出任何避免内核停止和重新启动的替代方法。 :D

【讨论】:

    猜你喜欢
    • 2015-11-13
    • 2015-01-28
    • 2017-06-02
    • 2019-11-26
    • 1970-01-01
    • 2020-10-31
    • 2018-10-28
    • 2022-11-14
    • 2021-07-13
    相关资源
    最近更新 更多