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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.