Move child folder contents to parent folder in python

Example using the os and shutil modules:

from os.path import join
from os import listdir, rmdir
from shutil import move

root = 'dstfolder/slave1'
for filename in listdir(join(root, 'slave')):
    move(join(root, 'slave', filename), join(root, filename))
rmdir(root)

I needed something a little more generic, i.e. move all the files from all the [sub]+folders into the root folder.

For example start with:

root_folder
|----test1.txt
|----1
     |----test2.txt
     |----2
          |----test3.txt

And end up with:

root_folder
|----test1.txt
|----test2.txt
|----test3.txt

A quick recursive function does the trick:

import os, shutil, sys 

def move_to_root_folder(root_path, cur_path):
    for filename in os.listdir(cur_path):
        if os.path.isfile(os.path.join(cur_path, filename)):
            shutil.move(os.path.join(cur_path, filename), os.path.join(root_path, filename))
        elif os.path.isdir(os.path.join(cur_path, filename)):
            move_to_root_folder(root_path, os.path.join(cur_path, filename))
        else:
            sys.exit("Should never reach here.")
    # remove empty folders
    if cur_path != root_path:
        os.rmdir(cur_path)

You will usually call it with the same argument for root_path and cur_path, e.g. move_to_root_folder(os.getcwd(),os.getcwd()) if you want to try it in the python environment.

Tags:

Python