Nhi Yen
Nhi Yen

Reputation: 45

os.remove - PermissionError: [WinError 32] The process cannot access the file because it is being used by another process

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

Upvotes: 0

Views: 8128

Answers (3)

Yasas Sanju
Yasas Sanju

Reputation: 1

I faced similar problem and found a solution for my code. I opened the task manager and found the background running python program and ended the task. Then I was able to run the code.

Upvotes: -1

Nhi Yen
Nhi Yen

Reputation: 45

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

Upvotes: 0

Roman Pavelka
Roman Pavelka

Reputation: 4181

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?

Upvotes: 0

Related Questions