Created
July 24, 2025 14:55
-
-
Save kenilt/ebcd82ace04f05e304e3dec97a187aa8 to your computer and use it in GitHub Desktop.
Flattens all files from subdirectories into a single base folder. This is helpful when your backups or exports are nested in many useless folders.
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 | |
import shutil | |
# Set your base folder here | |
base_folder = "/path/to/target/folder" | |
# Walk through all subdirectories (bottom-up to safely remove them) | |
for root, dirs, files in os.walk(base_folder, topdown=False): | |
for file in files: | |
# Skip hidden/system files | |
if file.startswith("._"): | |
continue | |
file_path = os.path.join(root, file) | |
dest_path = os.path.join(base_folder, file) | |
# Handle name conflicts by appending a number | |
counter = 1 | |
while os.path.exists(dest_path): | |
name, ext = os.path.splitext(file) | |
dest_path = os.path.join(base_folder, f"{name}_{counter}{ext}") | |
counter += 1 | |
# Move the file to the base folder | |
shutil.move(file_path, dest_path) | |
print(f"Moved {file} to {base_folder}") | |
# Try to remove the now-empty folder (but not the base folder) | |
if root != base_folder: | |
try: | |
os.rmdir(root) | |
print(f"Removed empty folder: {root}") | |
except OSError: | |
print(f"Could not remove folder (not empty?): {root}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment