Reputation: 103
I'm trying to write a nested while loop that will create n number of folders with n number of sub-directories. The problem with my current code is that the first folder created does not contain the sub-directories. Only the 2nd directory made contains the sub-directories. My goal is to write a program that runs a parametric sweep with groundwater modeling software, and I need these directories to save the results.
import subprocess, os
i = 1
j = 1
while i <= 2:
path = r'C:/Users/TEvans/Desktop/Testing/slope%d' % i
if not os.path.exists(path): os.makedirs(path)
os.chdir(path)
i = i+1
while j <= 3:
path1 = r'C:/Users/TEvans/Desktop/Testing/slope%d/r%d' % (i, j)
if not os.path.exists(path1): os.makedirs(path1)
j = j+1
Upvotes: 0
Views: 1315
Reputation: 168616
Some of your code is redundant, and (as others mentioned) the while
is confusing your math.
Here is a simpler, nearly equivalent version:
import os
for i in (1,2):
for j in (1,2,3):
path1 = r'C:/Users/TEvans/Desktop/Testing/slope%d/r%d' % (i, j)
if not os.path.exists(path1): os.makedirs(path1)
I removed the call to os.makedirs()
in the outer loop since those directories will be created by the inner loop's os.makedirs()
.
I fixed the math for both i
and j
to reflect what I believe you intended.
I removed the call to os.chdir()
because you are using absolute paths and the call appeared to be otherwise unnecessary.
Upvotes: 2
Reputation: 317
The problem is with the loop constructs. This should do the trick:
import subprocess, os
for i in range(0,2):
path = r'C:/Users/TEvans/Desktop/Testing/slope%d' % i
if not os.path.exists(path): os.makedirs(path)
os.chdir(path)
for j in range(0,3):
path1 = r'C:/Users/TEvans/Desktop/Testing/slope%d/r%d' % (i, j)
if not os.path.exists(path1): os.makedirs(path1)
The 'for' construct ensures that the variable is only incremented after the entire code-block has been executed, in stead of somewhere in between, as is the case in your code fragment.
Upvotes: 0
Reputation: 208435
Your problem is that i
has already been incremented before the inner while loop is entered, you could fix this by moving the i = i+1
line so that it is the last thing that is done in the while i <= 2
loop.
However a better solution would be to just use a for loop:
for i in range(1, 3):
path = r'C:/Users/TEvans/Desktop/Testing/slope%d' % i
if not os.path.exists(path): os.makedirs(path)
os.chdir(path)
for j in range(1, 4):
path1 = r'C:/Users/TEvans/Desktop/Testing/slope%d/r%d' % (i, j)
if not os.path.exists(path1): os.makedirs(path1)
Upvotes: 0
Reputation: 25693
When os.makedirs(path1)
is called for the first time i
is already incremented. If you used a foor loop the code would be not only cleaner but more correct.
Upvotes: 1