【发布时间】: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