0

[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!

Nhi Yen
  • 35
  • 1
  • 6
  • End what process? Some other program thinks the file is important and doesn't want you to delete it. – Peter Wood Jul 12 '21 at 08:37
  • You can check this answer to find out what process is using your text file: https://stackoverflow.com/a/39637414/4644059 and then terminate it. But termination doesn't sounds like a safe approach. – wisp Jul 12 '21 at 08:39

2 Answers2

0

Some other process has your file opened and you have to force that other process to close the file first, by killing it or by other way. More info available here:

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

Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28
0

Till now, I found out only 1 solution but it does not seem good to me, which is:

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)

The problem is, after this step, Kernel (Jupyter Notebook) must restart and run all from the beginning. Hope anyone could suggest any alternative way which avoids Kernel to stop & restart. :D

Nhi Yen
  • 35
  • 1
  • 6