Created
March 2, 2025 00:54
-
-
Save waka-wa/5ef4b6169e766b0702bf7b97c7a5a569 to your computer and use it in GitHub Desktop.
A minimal Python script that scans all subdirectories (except the "All" folder) in the current working directory and creates a unified "All" folder populated with symlinks to each file. It replicates the original folder structure within "All", offering a convenient aggregated view of files without moving them.
This file contains hidden or 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 | |
from pathlib import Path | |
def update_symlinks(base_path): | |
""" | |
Create/update an 'All' folder containing symlinks to files found in all | |
subdirectories of the base_path (except 'All' itself). The directory structure | |
is replicated: for each top-level folder, its internal structure is reproduced | |
inside the 'All' folder. | |
""" | |
base_dir = Path(base_path) | |
all_dir = base_dir / "All" | |
all_dir.mkdir(exist_ok=True) | |
# Remove broken symlinks within the "All" folder. | |
for item in all_dir.glob('**/*'): | |
if item.is_symlink() and not item.exists(): | |
try: | |
item.unlink() | |
print(f"Removed broken symlink: {item}") | |
except Exception as e: | |
print(f"Error removing broken symlink {item}: {e}") | |
created_symlinks = 0 | |
# Iterate over all subdirectories (skip "All") | |
for sub_dir in base_dir.iterdir(): | |
if sub_dir.is_dir() and sub_dir.name != "All": | |
# Walk through the subdirectory recursively. | |
for root, _, files in os.walk(sub_dir): | |
for file in files: | |
original_file = Path(root) / file | |
try: | |
# Get the relative path from the top-level subdirectory. | |
relative_path = Path(root).relative_to(sub_dir) | |
# Recreate the folder structure inside "All" under a folder named as the source folder. | |
symlink_dir = all_dir / sub_dir.name / relative_path | |
symlink_dir.mkdir(parents=True, exist_ok=True) | |
symlink_path = symlink_dir / file | |
if not symlink_path.exists(): | |
# Compute a relative target for the symlink. | |
target = os.path.relpath(original_file, symlink_dir) | |
symlink_path.symlink_to(target) | |
print(f"Created symlink: {symlink_path} -> {target}") | |
created_symlinks += 1 | |
else: | |
print(f"Symlink already exists: {symlink_path}") | |
except Exception as e: | |
print(f"Error creating symlink for {original_file}: {e}") | |
print(f"\nSymlink update complete: {created_symlinks} new symlinks created.") | |
if __name__ == "__main__": | |
base_path = os.getcwd() | |
print(f"Working in directory: {base_path}") | |
update_symlinks(base_path) | |
input("\nPress Enter to exit...") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment