2

I am using python 2.7. I want to delete a folder which may or may not be empty. The folder is handled by thread for file-monitoring. I am not able to kill thread but wanted to delete this folder any how. I tried with

os.rmdir(Location)
shutil.rmtree(Location) 
os.unlink(Location)

But, it didn't work. It is showing error as [Error 32] The process cannot access the file because it is being used by another process: 'c:\\users\\cipher~1\\appdata\\local\\temp\\fis\\a0c433973524de528420bbd56f8ede609e6ea700' I want to delete folder a0c433973524de528420bbd56f8ede609e6ea700 or delete whole path will also suffice.

class myThread (threading.Thread):
    def __init__(self, threadID, fileName, directory, origin):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.fileName = fileName
        self.daemon = True
        self.dir = directory
        self.originalFile = origin
    def run(self):
        startMonitor(self.fileName, self.dir, self.originalFile)

def startMonitor(fileMonitoring,dirPath,originalFile):
    logging.debug("in startMonitor")
    hDir = win32file.CreateFile (
      dirPath,
      FILE_LIST_DIRECTORY,
      win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
      None,
      win32con.OPEN_EXISTING,
      win32con.FILE_FLAG_BACKUP_SEMANTICS,
      None
    )
    logging.debug("Wait for new data and call ProcessNewData for each new chunk that's written")
    readFlags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME  | \
            win32con.FILE_NOTIFY_CHANGE_DIR_NAME   | \
            win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | \
            win32con.FILE_NOTIFY_CHANGE_SIZE       | \
            win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | \
            win32con.FILE_NOTIFY_CHANGE_SECURITY
    # Wait for new data and call ProcessNewData for each new chunk that's written
    while 1:
        # Wait for a change to occur
        results = win32file.ReadDirectoryChangesW (
                                                   hDir,
                                                   1024,
                                                   False,
                                                   readFlags,
                                                   None
                                                   )
        # For each change, check to see if it's updating the file we're interested in
        logging.debug("For each change, check to see if it's updating the file we're interested in")
        for action, file_M in results:
            full_filename = os.path.join (dirPath, file_M)
            #print file, ACTIONS.get (action, "Unknown")
            if len(full_filename) == len(fileMonitoring) and action == 3:
                #copy to main file
                if os.path.exists(originalFile):
                        encrypt_file(key,fileMonitoring,originalFile,iv)

 try:
        thread1 = myThread(1, FileName, Location,selectedFileName)
        thread1.start();
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
            logging.debug("control to file open subprocess")
            ss=subprocess.Popen(FileName,shell=True)
            ss.communicate()


            logging.debug("file open subprocess executed")
            removeTempFile(FileName)
            logging.debug("file removed")
            shutil.rmtree(Location) #to remove folder, I asked question for this ony.
            sys.exit(0)
    except Exception as e:
        print e
        logging.error(e)
        logging.debug("exception in encryption Thread")
        removeTempFile(FileName)
        sys.exit(e)
imp
  • 1,967
  • 2
  • 28
  • 40
  • 1
    Well, no process can delete the file unless the thread using it stops. That's the way windows work. (as far as I know) – shad0w_wa1k3r Nov 05 '13 at 07:22
  • @AshishNitinPatil how can I tell thread to stop using the file – imp Nov 05 '13 at 09:02
  • I don't know. The question is more suitable for http://superuser.com/ – shad0w_wa1k3r Nov 05 '13 at 09:05
  • 1
    @Ashish Nitin Patil: The error message says _another process_ is using it, **not** the current one which would be the one containing the running thread -- so I think you're incorrect. – martineau Nov 05 '13 at 09:21
  • @Harish, where is the code that spawns the thread that does use this file? When you remove the file, what do you want to happen if the thread is not done using/writing the file? Do you want to prematurely kill the thread? It appears that your other process is still using the file, so you cannot delete it. You need to wait for the other process or kill the other process – Paul Nov 05 '13 at 13:19
  • @martineau Yes, you are right, I overlooked that possibility. In that case, we need the code that spawns the thread. – shad0w_wa1k3r Nov 05 '13 at 15:47
  • @Paul Please check the code – imp Nov 06 '13 at 04:29
  • @martineau Please check the code – imp Nov 06 '13 at 04:31
  • @harish: OK, I have checked the code, and the info I found is consistent with what I said =- some _other_ process is using the file. One possibility is your anti-virus software. Several sources suggested using the [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) utility to find out which files processes have opened or loaded. Run it and click the Find menu, athen choose Find Handle or DLL, then type in the file name and click on the Search button. – martineau Nov 06 '13 at 09:39
  • @martineau ok sir, I also tested os.rmdir(Location) in different module of eclipse(code for removing that file only) , it removed successfully. Then I used Locker to identify which process is using the file, It gives that thread of file-monitor is using it. So, how to kill thread? – imp Nov 06 '13 at 12:49
  • I'm not sure the scenario you tested is bares on the matter at hand. Regardless, perhaps you can make the thread pause (and the optionally restart it). See this [answer](http://stackoverflow.com/a/13301661/355230) and this related [one](http://stackoverflow.com/questions/15729498/how-to-start-and-stop-thread/15734837#15734837) on that subject. – martineau Nov 06 '13 at 18:41
  • Sorry this is a super late post but perhaps could be useful to other. Using Python3 in a Windows OS I created a directory and was trying to delete it and was getting the same error. Eventually I discovered that my current working directory was the directory I was trying to remove. By changing `os.chdir("..")` my working directory `shutil.rmtree(path)` worked without raising an error. – CodeAddictJack Apr 01 '19 at 19:17

0 Answers0