Skip to content Skip to sidebar Skip to footer

Move Child Folder Contents To Parent Folder In Python

I have a specific problem in python. Below is my folder structure. dstfolder/slave1/slave I want the contents of 'slave' folder to be moved to 'slave1' (parent folder). Once moved,

Solution 1:

Example using the os and shutil modules:

from os.path import joinfrom 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)

Solution 2:

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 inos.listdir(cur_path):
        ifos.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.

Solution 3:

The problem might be with the path you specified in the shutil.move function

Try this code

import os
import shutil
for r,d,f inos.walk("slave1"):
    for files in f:
        filepath = os.path.join(os.getcwd(),"slave1","slave", files)
        destpath = os.path.join(os.getcwd(),"slave1")
        shutil.copy(filepath,destpath)

shutil.rmtree(os.path.join(os.getcwd(),"slave1","slave"))

Paste it into a .py file in the dstfolder. I.e. slave1 and this file should remain side by side. and then run it. worked for me

Solution 4:

Maybe you could get into the dictionary slave, and then

execsystem('mv .........')

It will work won't it?

Post a Comment for "Move Child Folder Contents To Parent Folder In Python"