Search code examples
pythonshutilos.walkpython-os

os.walk one level down


I have a folder (A) that is structured like this:

A\b
A\c
A\d

I would like to copy folder b, c, and d one level down 3 times like this:

A\b\b1\b2\b3
A\c\c1\c2\c3
A\d\d1\d2\d3

Where b1,b2, and b3 are copies of the folder b, the same goes for c and d.

When I run the code below I end up with the desired structure but also adds three copies in each sub-folder so A\b\b1 has b1,b2, and b3 folders. The problem has to do with the loop but I can't pinpoint it

import os
import sys
import shutil

list1= [1,2,3]
path = "C:\ladg\oner"
root, dirs, files = os.walk(path).next()

for dir in dirs:
    for i in list1:
        new_folder_path = os.path.join(root,dir, dir+ str(i))
        shutil.copytree(os.path.join(root, dir), new_folder_path)

Solution

  • Try this. You're currently iterating through the list without changing directories.

    import os
    import sys
    import shutil
    
    list1= [1,2,3]
    path = "C:\ladg\oner"
    root, dirs, files = os.walk(path).next()
    
    for dir in dirs:
        curr_path = os.path.join(root, dir)
        for i in list1:
            new_folder_path = os.path.join(curr_path, dir + str(i))
            shutil.copytree(curr_path, new_folder_path)
            os.chdir(new_folder_path)
            curr_path = new_folder_path
    

    In a follow-up question, if you want to achieve a scenario where you have this resulting directory:

    A
    -- b
       -- b1
       -- b2 
       -- b3
    -- c
       -- c1
       -- c2
       -- c3
    

    You can use the following code. This is different from the first suggestion as now you're creating a tmp_dir to store your copies before finally replacing the old curr_dir with this new tmp_dir. This is necessary to maintain an intact copy of curr_dir when you do subsequent copies.

    import os
    import sys
    import shutil
    
    list1= [1,2,3]
    path = "~/A"
    root, dirs, files = os.walk(path).next()
    
    for dir in dirs:
        curr_dir = os.path.join(root, dir)
        tmp_dir = os.path.join(root, "tmp_" + dir)
        os.mkdir(tmp_dir)
        for i in list1:
            new_folder_path = os.path.join(tmp_dir, dir+ str(i))
            shutil.copytree(curr_dir, new_folder_path)
        shutil.rmtree(curr_dir)
        shutil.move(tmp_dir, curr_dir)