Search code examples
pythondirectoryfile-move

Recursively move all files on subdirectories to another directory in Python


The title explains what I am after. Note that the sub directories won't contain any directories only files (*.JPG). Essentially, just moving everything up one level in the file tree.

For example, from ~/someDir/folder1/* , ~/someDir/folder2/* , ... , ~/someDir/folderN/*. I want all of the contents of the sub directories brought up to ~/someDir/.


Solution

  • shutil.move is a good option to move files.

    import shutil
    import os
    
    source = "/parent/subdir"
    destination = "/parent/"
    files_list = os.listdir(source)
    for files in files_list:
        shutil.move(files, destination)
    

    For Recursive move, you can try shutil.copytree(SOURCE, DESTINATION). it just copies all files and if needed you can manually cleanup the source directory.