2
votes

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.

2
Sounds tailor-made for a recursive function.Hugh Bothwell
Yes, but I don't know how to continue after thisadb16x
so the user enters 1 number or 2?Padraic Cunningham
The user enters can number they like (less than 50, since it is an exponential function).adb16x
As in the example, they are to be named like: Folder1, Folder2 .....adb16x

2 Answers

1
votes

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
1
votes

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("..")