0

I am working on a python script in which i am trying to delete all the files which are there within the given folder , though few errors like below are acting as a road block due to which the code is not able to complete.

PermissionError: The process cannot access the file because it is being used by another process: C: \\users\\dhoni\\AppData\\Local\\Temp\\2735ad90-sfa3-412f-b6b1-54534646ff3.tmp'

my question is using shutil library how can i delete all the files from a specific folder or it is possible to delete files from two different folders ?

Tried the below code

`
import shutil
import os 
location = r"C:\Users\dhoni\AppData\Local"
dir = "Temp"
path = os.path.join(location, dir)
shutil.rmtree(path)`
Fatemeh Sangin
  • 558
  • 1
  • 4
  • 19
  • a quick google I found this, `shutil.rmtree(path, ignore_errors=True, onerror=None)`. I don't actually know but worth a shot. – Joe_DM Nov 11 '22 at 12:27
  • i have tried ignore_errors=True but that doesn't help, the files are still there – user20432746 Nov 11 '22 at 12:28
  • when you say the files are still there, is it just the files that had errors. Or does it fail to touch the ones that didn't have any errors too? If you don't have access to delete the file or it's locked for another reason then I don't think it'll be possible. – Joe_DM Nov 11 '22 at 12:37
  • I found this too, maybe it can help? https://stackoverflow.com/questions/2656322/shutil-rmtree-fails-on-windows-with-access-is-denied/2656405#2656405 – Joe_DM Nov 11 '22 at 12:39
  • not sure why but its not deleting a single file from that particular folder, i have tested it on my personal machine as well – user20432746 Nov 11 '22 at 12:54
  • can you test on a different folder that you definitely have access to? maybe it can't access any files in the folder. you could even have the app create test files, set one of the test files to read only (to force a fail) and then run the function. this test will demonstrate if it's permissions or code related. sorry I can't be of more help. – Joe_DM Nov 11 '22 at 12:56

2 Answers2

1

As @eDonkey already wrote, shutil.rmtree only can delete folders not files. With os.remove you can delete files itself. The problem still is you dont have permissions. If you want to force delete everything inside that temp folder you can compile your code and run it as administrator. Problem with that is, that programs could crash when working with one of that file that got deleted. I experienced that with multiple programms (some of the programms where working with databases -> so pretty bad idea). I would advise not force delete the temp.

I already wrote some kind of code that is deleting the users temp. Its definetly not fancy but it works ;). Maybe you can copy some if it or get the idea of what it is doing.

import os, shutil, sys


def get_current_user():
    return os.getlogin()

def temp_deletion(user):
    error_count = 0
    error_list = []

    user_temp_path = f"C:/Users/{user}/AppData/Local/Temp"
    if os.path.exists(user_temp_path):
        for file in os.listdir(user_temp_path):
            file_path = f"{user_temp_path}/{file}"
            # Deletion for Files
            if os.path.isfile(file_path):
                try:
                    os.remove(file_path)

                except Exception as e:
                    error_count += 1
                    error_list.append(e)

            # Deletion for Folders
            elif os.path.isdir(file_path):
                try:
                    shutil.rmtree(file_path)
                except Exception as e:
                    error_count += 1
                    error_list.append(e)
    else:
        print("No tempfolder found!")
        print(f"{user_temp_path}")

if __name__ == '__main__':
    user = get_current_user()
    temp_deletion(user)

    print("Finished!")
    sys.exit()
LiiVion
  • 312
  • 1
  • 10
0

It doesn't delete any files because rmtree deletes the entire directory, which cannot happen because at least one file in the directory is still used by another process. If you want to delete the directory, you'll have to make sure, that none of the files are used by another process.

Based on your question though, I'm making the assumption, that you want to delete the files inside the directory and not the directory itself.

To delete a file you'll have to use the os module, specifically os.remove() - the shutil module doesn't provide a function to delete files.

Which could look like the following:

import os 
location = r"C:\Users\dhoni\AppData\Local"
dir = "Temp"
path = os.path.join(location, dir)
files = [f for f in os.listdir(path)]

for f in files:
    try:
        os.remove(os.path.join(path, f))
    except:
        print("Error while deleting file", f)

This will delete all the files (which are not used by another process) in the specified directory.

eDonkey
  • 606
  • 2
  • 7
  • 25