|
| 1 | +import os |
| 2 | +import shutil |
| 3 | + |
| 4 | +FILE_TYPES = { |
| 5 | + "PDFs": [".pdf"], |
| 6 | + "Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff"], |
| 7 | + "ZIP_Files": [".zip", ".rar", ".7z", ".tar", ".gz"], |
| 8 | + "Executables": [".exe", ".msi", ".bat"], |
| 9 | + "Documents": [".doc", ".docx", ".txt", ".odt", ".rtf"], |
| 10 | + "Videos": [".mp4", ".mkv", ".avi", ".mov"], |
| 11 | +} |
| 12 | + |
| 13 | +downloads_folder = os.path.expanduser("~/Downloads") |
| 14 | + |
| 15 | +def create_folder(folder_path): |
| 16 | + if not os.path.exists(folder_path): |
| 17 | + os.makedirs(folder_path) |
| 18 | + |
| 19 | +def get_unique_destination(destination_folder, filename): |
| 20 | + base, ext = os.path.splitext(filename) |
| 21 | + counter = 1 |
| 22 | + new_filename = filename |
| 23 | + dest_path = os.path.join(destination_folder, new_filename) |
| 24 | + while os.path.exists(dest_path): |
| 25 | + new_filename = f"{base}{counter}{ext}" |
| 26 | + dest_path = os.path.join(destination_folder, new_filename) |
| 27 | + counter += 1 |
| 28 | + return dest_path |
| 29 | + |
| 30 | +def move_file(file_path, destination_folder): |
| 31 | + create_folder(destination_folder) |
| 32 | + filename = os.path.basename(file_path) |
| 33 | + destination = get_unique_destination(destination_folder, filename) |
| 34 | + try: |
| 35 | + shutil.move(file_path, destination) |
| 36 | + print(f"Moved: {filename} -> {destination}") |
| 37 | + except Exception as e: |
| 38 | + print(f"Error moving {file_path}: {e}") |
| 39 | + |
| 40 | +def auto_sort_downloads(): |
| 41 | + for item in os.listdir(downloads_folder): |
| 42 | + item_path = os.path.join(downloads_folder, item) |
| 43 | + if os.path.isdir(item_path): |
| 44 | + continue |
| 45 | + _, ext = os.path.splitext(item) |
| 46 | + ext = ext.lower() |
| 47 | + sorted_file = False |
| 48 | + for folder_name, extensions in FILE_TYPES.items(): |
| 49 | + if ext in extensions: |
| 50 | + destination = os.path.join(downloads_folder, folder_name) |
| 51 | + move_file(item_path, destination) |
| 52 | + sorted_file = True |
| 53 | + break |
| 54 | + if not sorted_file: |
| 55 | + destination = os.path.join(downloads_folder, "Others") |
| 56 | + move_file(item_path, destination) |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + auto_sort_downloads() |
0 commit comments