How to skip permission error while deleting all files from a folder

Question:

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:UsersdhoniAppDataLocal"
dir = "Temp"
path = os.path.join(location, dir)
shutil.rmtree(path)`
Asked By: user20432746

||

Answers:

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:UsersdhoniAppDataLocal"
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.

Answered By: eDonkey

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()
Answered By: LiiVion
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.