Home > Net >  PermissionError: [WinError 32] The process cannot access the file because it is being used by anothe
PermissionError: [WinError 32] The process cannot access the file because it is being used by anothe

Time:01-14

I need help on the issue I am having. "PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:".

So the script below deletes a folder with an excel file in it. However, if the excel file is opened, it doesn't proceed on the shutil.rmtree(dirpath) command. Can somebody lead me to a solution where user will be prompt when the file is opened? Looking forward to your feedback. Thank you very much in advance.

import os
import shutil

dirpath = os.path.join('C:/Path/Folder', 'Folder')
if os.path.exists(dirpath) and os.path.isdir(dirpath):
   shutil.rmtree(dirpath)
   print('Deleted.')

else:
   print('Folder does not exist!')
   messagebox.showinfo('Ok.')

CodePudding user response:

Given that you are using Windows, I would say try the following:

import os
import shutil

dirpath = os.path.join('C:/Path/Folder', 'Folder')
if os.path.exists(dirpath) and os.path.isdir(dirpath):
   try:
       os.rename(dirpath, dirpath)
       shutil.rmtree(dirpath)
       print('Deleted.')
   except:
       messagebox.showinfo('File opened by another process')

else:
   print('Folder does not exist!')
   messagebox.showinfo('Ok.')
  • Related