Flatten complex directory structure in Python

directory-structure, file-move, flatten, python

Solution

Run recursively through directory, move the files and launch `move` for directories:

import shutil
import os

def move(destination, depth=None):
    if not depth:
        depth = []
    for file_or_dir in os.listdir(os.path.join([destination] + depth, os.sep)):
        if os.path.isfile(file_or_dir):
            shutil.move(file_or_dir, destination)
        else:
            move(destination, os.path.join(depth + [file_or_dir], os.sep))

Problem

I want to move files from a complex directory structure to just one place. For example i have this deep hierarchy: ``` foo/ foo2/ 1.jpg 2.jpg ... ``` I want it to be: ``` 1.jpg 2.jpg ... ``` My current solution: ``` def move(destination): for_removal = os.path.join(destination, '\\') is_in_parent = lambda x: x.find(for_removal) > -1 with directory(destination): files_to_move = filter(is_in_parent, glob_recursive(path='.')) for file in files_to_move: shutil.move(file, destination) ``` Definitions: `directory` and `glob_recursive`. Note, that my code only moves files to their common parent directory, not an arbitrary destination. How can i move all files from a complex hierarchy to a single place succinctly and elegantly?

Original source

Related problems