Reputation: 21961
Is there a way to delete a folder in python if it does not contain any files? I can do the foll:
os.rmdir() will remove an empty directory.
shutil.rmtree() will delete a directory and all its contents.
If the folder has empty sub-folders, it should be deleted too
Upvotes: 1
Views: 471
Reputation: 11477
os.removedirs(path)
Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty).
e.g.
import os
if not os.listdir(dir):
os.removedirs(dir)
See more details from os.removedirs.
Hope this helps.
Upvotes: 2