Created
August 14, 2023 19:23
-
-
Save wiljdaws/8c50eba05bed4992d3dd9fee64eed7ce to your computer and use it in GitHub Desktop.
Delete empty folders in path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import logging | |
# if log folder does not exist create it | |
if not os.path.exists('main\log'): | |
os.makedirs('main\log') | |
logging.basicConfig(filename='main\log\deleted_folders.log', | |
level=logging.INFO, | |
format='%(asctime)s - %(levelname)s - %(message)s') | |
def remove_empty_folders(folder_path): | |
''' | |
Remove empty folders from a given path. | |
* Parameters\n | |
\t - folder_path: path to the folder \n | |
* Return\n | |
\t - None: removes empty folders and logs them in deleted_folder.log file | |
Example use: | |
>>> remove_empty_folders("C:\\Users\\user1") | |
''' | |
walk = list(os.walk(folder_path)) | |
for path, _, _ in walk[::-1]: | |
if len(os.listdir(path)) == 0: | |
# log removed path | |
logging.info(f'removed empty folder {path}') | |
os.rmdir(path) | |
if __name__ == '__main__': | |
remove_empty_folders("2023") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment