Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete multiple directories in python

In python, I understand that I can delete multiple files with the same name using the following command for eg:

for f in glob.glob("file_name_*.txt"):
    os.remove(f)

And that a single directory can be deleted with shutil.rmtree('/path/to/dir') - and that this command will delete the directory even if the directory is not empty. On the other hand, os.rmdir() needs that the directory be empty.

I actually want to delete multiple directories with the same name, and they are not empty. So, I am looking for something like shutil.rmtree('directory_*')

Is there a way to do this with python?

like image 749
Nanditha Avatar asked May 15 '26 06:05

Nanditha


1 Answers

You have all of the pieces: glob() iterates, and rmtree() deletes:

for path in glob.glob("directory_*"):
    shutil.rmtree(path)

This will throw OSError if one of the globbed paths names a file, or for any other reason that rmtree() can fail. You can add error handling as you see fit, once you decide how you want to handle the errors. It doesn't make sense to add error handling unless you know what you want to do with the error, so I have left error handling out.

like image 78
Dietrich Epp Avatar answered May 17 '26 20:05

Dietrich Epp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!