Вопрос

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?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top