2

I am trying to create a number of nested folders in python.

Objective: 1) Ask user for a number (Let us say 3) 2) Create 3 folders. 3) Inside each folder, there should be 3 folders. This nesting should be done 3 times.

Example:

Folder1 

Folder1 Folder2 Folder3

Folder1 Folder2 Folder3

Folder1 Folder2 Folder3

Folder2 

Folder1 Folder2 Folder3

Folder1 Folder2 Folder3

Folder1 Folder2 Folder3

Folder3 

Folder1 Folder2 Folder3

Folder1 Folder2 Folder3

Folder1 Folder2 Folder3

This is my current code:

import os
i = 0
num = 0
while i<17:
    num+=1
    name="Python"+ str(num)
    i+=1

This is only for creating the first set of folders (I have taken 17). Help would be much appreciated.

(I am running Windows)

EDIT:

For a more clearer example : http://s9.postimg.org/sehux992n/20141228_201038.jpg

(Taking 3 as the user input)

From the image, we can see that there are 3 layers.

adb16x
  • 658
  • 6
  • 24

2 Answers2

1

Partial code, feel free to fill in the blanks:

def recursive_make_folders(path, width, depth):
    for i in range(1, width + 1):
        folder_name = make_folder_name(i)
        make_folder(path + folder_name)
        if depth > 1:
            recursive_make_folders(path + folder_name, width, depth - 1)

Keep in mind, this will create width ** depth folders, which can be a very large number, especially as depth increases.

Edit:

  • where I show path + folder_name, you will need to actually use os.path.join(path, folder_name)
  • make_folder should become os.mkdir
  • if you want the code to run in the current directory, you can use "." as the initial path
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
1

You cannot have subdirectories with the same names inside the folder. If you want to add input * input directories with different names:

import os

inp = int(raw_input())

folders = [("Folder{}".format(i)) for i in xrange(1,inp+1)]
for dr in xrange(1,inp+1):
    os.makedirs("Folder{}".format(dr))
for fold in folders:
    os.chdir(fold)
    for i in xrange(1, inp*inp+1):
        os.makedirs("Folder{}".format(i))
    os.chdir("..")

Maybe this is closer to what you want:

import os

inp = int(raw_input())

folders = [("Folder{}".format(i)) for i in xrange(1, inp+1)]
for fold in folders:
    os.makedirs(fold)
    os.chdir(fold)
    for fold in folders:
        os.mkdir(fold)
        os.chdir(fold)
        for fold in folders:
            os.mkdir(fold)
        os.chdir("..")
    os.chdir("..")
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • @WhiteFlameAB, I am a little unsure of your nesting requirement as I said in my comment, can you add a single complete folder tree when the input is 3. Once I can understand exactly what you mean it is just a matter of nesting a for loop – Padraic Cunningham Dec 28 '14 at 16:44
  • I have added a link that better explains the nesting – adb16x Dec 28 '14 at 17:15