1

I am trying to create a directory. If the name already exists, then it appends "_1" to the directory name recursively.

This runs fine if the directory does not exist already. It also runs fine if the directory already exists (it creates directory+"_1" and returns the same). However, if the directory + "_1" already exists, then the function creates directory+"_1_1" but returns None.

import os

def recurs_mkdir(out_dir):
    try:
        os.mkdir(out_dir)
    except OSError:
        out_dir += "_1"
        recurs_mkdir(out_dir)
    else:
        print "Returning: %s" % out_dir
        return out_dir

>>> print recurs_mkdir("existing_folder")
Returning: existing_folder_1
None

Why does it return None in the case of an exception?

EDIT: Nneoneo's answer works if "exisiting_folder" exists, but does not behave properly if "existing_folder" and "existing_folder_1" exist. Modified, the function is

import os

def recurs_mkdir(out_dir):
    try:
        os.mkdir(out_dir)
    except OSError:
        out_dir += "_1"
        recurs_mkdir(out_dir)
        print "Returning: %s" % out_dir
        return out_dir
    else:
        print "Returning: %s" % out_dir
        return out_dir

If "existing_folder" is already created:

>>> recurs_mkdir("existing_folder")
Returning: existing_folder_1
Returning: existing_folder_1
existing_folder_1

If "existing_folder" and "existing_folder_1" already exist:

>>> recurs_mkdir("existing_folder")
Returning: existing_folder_1_1
Returning: existing_folder_1_1
Returning: existing_folder_1
existing_folder_1

EDIT 2: Answer from Nneoneo

import os

def recurs_mkdir(out_dir):
    try:
        os.mkdir(out_dir)
    except OSError:
        out_dir += "_1"
        return recurs_mkdir(out_dir)
    else:
        print "Returning: %s" % out_dir
        return out_dir
Manila Thrilla
  • 547
  • 1
  • 8
  • 17

1 Answers1

4

Because no return statement is invoked at all in case of an exception, the function returns the default value of None (this is the same return value you'd get if you wrote a bare return statement without a return value).

Add a return statement to the except clause to return whatever you want.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • No clue, wasn't me. I like your answer, but it doesn't seem to work quite right if, say, you have "existing_folder" and "existing_folder_1" and you run recurs_mkdir("existing_folder"). – Manila Thrilla Apr 11 '14 at 00:15
  • 3
    What you really need to do is just `return recurs_mkdir(out_dir)`. That way, whatever final directory was *actually* created will be returned by the innermost `recurs_mkdir` call, and passed back up the stack. – nneonneo Apr 11 '14 at 00:20