Skip to content

Instantly share code, notes, and snippets.

@Mlawrence95
Last active October 21, 2019 23:38
Show Gist options
  • Save Mlawrence95/77edd40ec8ff4ee53f69a681aa61669e to your computer and use it in GitHub Desktop.
Save Mlawrence95/77edd40ec8ff4ee53f69a681aa61669e to your computer and use it in GitHub Desktop.
** DESTRUCTIVE CODE -- DON'T COPY AND PASTE WITHOUT READING** Unpacks folders at the specified location to one level. Can be applied recursively to flatten everything if desired.
import os
import shutil
def flatten_directory(directory, delete_after=False):
"""
Flattens all folders in directory, deleting the empty folders after.
**WARNING**
This code WILL DELETE YOUR FILES
if used naively. Seriously.
"""
directory = os.path.abspath(directory)
for file in os.listdir(directory):
full_path = directory + f'/{file}'
if os.path.isdir(full_path):
for path in os.listdir(full_path):
try:
shutil.move(os.path.join(full_path, path), directory)
except FileNotFoundError:
print(f'Could not find {path}')
if delete_after:
shutil.rmtree(full_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment