Sometimes you want to delete a folder in Python. You know that os.rmdir() can do that for you. But then you realize it can only remove empty folders. If you want to remove the content before deleting the folder you come up with:
def remove_non_empty_dir(path_to_dir): if os.path.exists(path_to_dir): files_in_dir = os.listdir(path_to_dir) for file in files_in_dir: os.remove(os.path.join(path_to_dir, file)) os.rmdir(path_to_dir)
And then you remember someone already solved this problem for you 🙂
Table of Contents
shutil
import shutil shutil.rmtree('./build')
Bazinga!
More cool stuff to do with shutil
Copy
shutil.copy("./dir_one/test.txt", "./dir_two")
Move
shutil.move("./dir_one/test.txt", "./dir_two")
Archive
shutil.make_archive("./dir_one", format="zip")