I have this code:
global dir_name
dir_name = ''
def generateDirectoryName(newpath, x=0):
while True:
dir_name = (newpath + ('_' + str(x) if x != 0 else '')).strip()
if not os.path.exists(dir_name):
os.mkdir(dir_name)
#1
#print(dir_name)
return dir_name
else:
x = x + 1
def createDirectory():
generateDirectoryName(newpath)
def main():
cwd = os.getcwd()
createDirectory()
#2
print(dir_name)
main()
#3
print(dir_name)
When I try the code, the two print
s at the end (labelled with comments 2
and 3
don’t appear to have any effect. However, if I uncomment the print
inside the function (at comment 1
), it will show the dir_name
value. Why does this happen – why can’t I access dir_name
outside the function? How can I fix the problem?
>Solution :
dir_name is a local variable in your function. In order to change it to global you have to use global dir_name inside the function. As far as printing goes, dir_name is actually getting printed at 2 and 3 but is just an empty string. Also, you dont have to return dir_name as you’re not assigning the return value of generateDirectoryName(newpath, x=0) to anything in createDirectory. Here is an updated version of your code:
dir_name = ''
def generateDirectoryName(newpath, x=0):
global dir_name
while True:
dir_name = (newpath + ('_' + str(x) if x != 0 else '')).strip()
if not os.path.exists(dir_name):
os.mkdir(dir_name)
#1
#print(dir_name)
return
else:
x = x + 1
def createDirectory():
generateDirectoryName(newpath)
def main():
cwd = os.getcwd()
createDirectory()
#2 (This will still print an empty string)
print(dir_name)
main()
#3 (This will print whatever is printed in #1)
print(dir_name)