Created
July 18, 2023 14:26
-
-
Save adujardin/3e0e94114237f67c3434d1e8dfaa5303 to your computer and use it in GitHub Desktop.
Remove folder matching name recursively and file with specific extension
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 shutil | |
from concurrent.futures import ThreadPoolExecutor | |
def remove_file(file_path): | |
try: | |
os.remove(file_path) | |
print(f"File '{file_path}' removed successfully.") | |
except Exception as e: | |
print(f"Failed to remove file '{file_path}': {e}") | |
def remove_folder(folder_path): | |
try: | |
shutil.rmtree(folder_path) | |
print(f"Folder '{folder_path}' removed successfully.") | |
except Exception as e: | |
print(f"Failed to remove folder '{folder_path}': {e}") | |
def remove_folders_and_files(root_dir, folder_names_to_remove, file_extension_to_remove, num_threads=1): | |
with ThreadPoolExecutor(max_workers=num_threads) as executor: | |
for dirpath, dirnames, filenames in os.walk(root_dir, topdown=True): | |
for filename in filenames: | |
if filename.endswith(file_extension_to_remove): | |
file_path = os.path.join(dirpath, filename) | |
executor.submit(remove_file, file_path) | |
for dirname in dirnames[:]: | |
if dirname in folder_names_to_remove: | |
folder_path = os.path.join(dirpath, dirname) | |
executor.submit(remove_folder, folder_path) | |
if __name__ == "__main__": | |
root_directory = "/path/to/your/root_directory" # Replace with the actual root directory path | |
folders_to_remove = ["folder_name_1", "folder_name_2", "folder_name_3"] # Replace with the folder names you want to remove | |
file_extension_to_remove = ".txt" # Replace with the file extension you want to remove | |
num_threads = 4 # Replace with the desired number of threads | |
remove_folders_and_files(root_directory, folders_to_remove, file_extension_to_remove, num_threads) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment