Why does this not work? (os.makedirs)

Your code will not even execute because you have a syntax error in your code:

if p3=='no':
    os.makedirs(oq+'\\'+ow+'\\'+oe)
if p4=='no':
    os.makedirs(oq+'\\'+ow+'\\'+oe+'\\'+oee)) # <-- here
if p5=='no':
    os.makedirs(oq+'\\'+ow+'\\'+oe+'\\'+oee+'\\'+ot)

Indeed:

$ python machdirs2.py 
  File "machdirs2.py", line 48
    os.makedirs(oq+'\\'+ow+'\\'+oe+'\\'+oee))
                                        ^
SyntaxError: invalid syntax
$ 

When you fix that syntax error, we see that you use input which would require you to quote your "input". I did that and entered two quoted dir names and then "no" just to hit a break that quits the while without processing the makedirs if-spaghetti. I have not digged deeper…

A better way to achieve your objective would be to start all over, rethink and then implement it from scratch avoiding all the tediuous repetitions and the pitfalls in your code:

import os

path = ""
while True:
    nxt = raw_input("next level or empty to quit: ")
    if not nxt:
        break
    path = os.path.join(path, nxt)

print path
os.makedirs(path)

resulting in:

$ python machdirs.py 
next level or empty to quit: a
next level or empty to quit: b
next level or empty to quit: c
next level or empty to quit: 
a/b/c
$ find . -type d -print
.
./a
./a/b
./a/b/c
$ 

Try the code on your Windows machine and you will see that it works cross-platform while your code yould not work on my Linux machine.

Leave a Comment