3

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

11 Comments

Could someone explain how this doesn't answer the question?
doesn't actually check that it's a directory. consider including if os.path.isdir or something..
@wim: That's grounds for a comment or edit, not a downvote. Use the system.
You could wrap the shutil.rmtree in a try: except OSError:` block. That would solve all the above issues.
Since it's not clear how the poster wants to handle errors, passing the exception up seems like decent default behavior to me.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.