import os def delete_files_and_empty_folders(): substrings = ['png', 'jpg', 'jpeg', 'pdf', 'gif', 'svg', 'webp', 'docx', '.tif', '.eps', 'bmp', 'psd', 'mp4', 'mp3', 'mpeg'] size_limit_kb_up = 50 # Files smaller than 1 KB will be deleted size_limit_kb_low = 4 main_folder = 'blogs' num = 0 # Walk through the main folder to delete files based on name and size criteria for root, dirs, files in os.walk(main_folder, topdown=False): for file in files: file_path = os.path.join(root, file) # Check if any of the substrings are in the file name and if the file size is below the limit if any(substring in file.lower() for substring in substrings) or os.path.getsize(file_path) > size_limit_kb_up * 1024 or os.path.getsize(file_path) < size_limit_kb_low * 1024: num = num + 1 try: os.remove(file_path) # Delete the file #print(f"Deleted file: {file_path}") except Exception as e: print(f"Error deleting file {file_path}: {e}") # After deleting files, check for empty folders and delete them for dir_name in dirs: dir_path = os.path.join(root, dir_name) # If the directory is empty, remove it if not os.listdir(dir_path): # Checks if the directory is empty try: os.rmdir(dir_path) print(f"Deleted empty folder: {dir_path}") except Exception as e: print(f"Error deleting folder {dir_path}: {e}") print(num) # Specify your main folder path, substrings to search for, and size limit in KB def delete_files_from_paths(): file_path = 'posts_done.txt' num =0 try: # Open and read the file paths from the .txt file with open(file_path, 'r') as f: paths = f.read().strip().strip('[]').replace("'", "").split(',') # Remove leading/trailing whitespaces from each path paths = [path.strip() for path in paths] # Attempt to delete each file for path in paths: if os.path.isfile(path): os.remove(path) print(f"Deleted: {path}") else: print(f"File not found or not a file: {path}") num = num + 1 print(num) except Exception as e: print(f"An error occurred: {e}") # # Example usage # delete_files_from_paths("posts_done.txt")