[Python] I try many suggestions in other posts and could not solve the 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)
The full error message is:
---------------------------------------------------------------------------
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'
As I know, after using copyfile, the file is closed by itself? Previously I also had the same trouble with os.rename. I found a manual method which is end process in Microsoft Resource Monitor but it seems not dynamic. Wanna find a solution right in the code itself.
Much appreciate your help in advance!