I'm trying to remove all files found in a directory. The accepted answer to Delete Folder Contents in Python suggests getting a list of all files and calling "unlink" on them in a loop.
Suppose I have thousands of files on a network share, and want to tie up the directory for as short a time as possible.
Is it more efficient to delete them all using a shell command like rm -f /path/*
or by using shutils.rmtree
or some such?
To delete multiple files, just loop over your list of files and use the above os. rmdir() function. To delete a folder containing all files you want to remove have to import shutil package. Then you can remove the folder as follows.
Navigate to the folder that you want to delete (with all its files and subfolders). Use cd *path*, for example, cd C:\Trash\Files\ to do so. Use cd .. to navigate to the parent folder and run the command RMDIR /Q/S *foldername* to delete the folder and all of its subfolders.
If you actually want to delete the whole directory tree, shutils.rmtree
should be faster than os.remove
(which is the same as os.unlink
). It also allows you to specify a callback function to handle errors.
The suggestion in the comment by @nmichaels is also good, you can os.rename
the directory then make a new one in its place and use shutils.rmtree
on the original, renamed directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With