PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: (Open Excel File) in Python

Question:

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.')
Asked By: JoeCastro

||

Answers:

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.')
Answered By: srdg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.