lpkej
lpkej

Reputation: 485

Kill file process before deletion using Python

how to kill a file process before deteling it? I'm deleting 200+ files, do I need to sleep the process?

The remove function I have:

    def remove_func(self, temp_url):
        for root, dirs, files in os.walk(temp_url):
            for f in files:
                file_path = os.path.join(root, f)
                try:
                    os.unlink(file_path)
                except PermissionError:
                    pid = subprocess.check_output(['pidof','-s',file_path])
                    os.kill(os.getpgid(pid))
                    # or I put the 'continue' in this exception block if the file is used in other processes 
            for d in dirs:
                if os.path.isdir(os.path.join(root, d)):
                    try:
                        shutil.rmtree(os.path.join(root, d))
                    except PermissionError:
                        continue

I get exception:

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

For my case the file left not removed has .jar.md5 extension.

Upvotes: 3

Views: 1135

Answers (1)

lpkej
lpkej

Reputation: 485

So it seems other processes may have been running in the background who caused this:

The process cannot access the file because it is being used by another process: error.

Code above works fine.

Upvotes: 2

Related Questions