I use Path.iterdir()
to go through a list of directories and do so some work.
from pathlib import Path
for folder in repository.iterdir():
# do some work
After completing that task, if it's successful the directories should be empty. I'm aware that you shouldn't modify a list you're iterating over, so doing this I assume would be bad practice, correct?
for folder in repository.iterdir():
folder.rmdir()
Instead what I did was collect a list of directories that are empty and then use that list to remove the directories, like this:
# Get a list of all the directories that are empty.
directories_to_remove = [folder for folder in repository.iterdir() if not os.listdir(folder)]
# Remove all the directories that are empty
for folder in directories_to_remove:
folder.rmdir()
The folder paths still exists in directories_to_remove
so I'm not modifying a list I'm iterating over, is this the correct way to delete the directories from the drive?