Reputation: 3
I made this little python 3 script to create folders with day-month-year names, from 16-09-2020 to 16-10-2020:
import os
# starting values for day, month and year
parent_dir = 'C:\\Users\\locale\\Desktop\\DIRS\\'
day_int = 16
month_int = 9
year_int = 2020
def gen_day_str():
if len(str(day_int)) == 1:
day_str = '0' + str(day_int)
elif len(str(day_int)) == 2:
day_str = str(day_int)
else:
print('error! exiting...')
exit()
def gen_month_str():
if len(str(month_int)) == 1:
month_str = '0' + str(month_int)
elif len(str(month_int)) == 2:
month_str = str(month_int)
else:
print('error! exiting...')
exit()
def gen_year_str():
year_str = str(year_int)
def gen_dir_name():
gen_day_str()
gen_month_str()
gen_year_str()
dir_name = day_str + '-' + month_str + '-' + year_str
while day_int <= 30:
gen_dir_name()
os.mkdir(parent_dir + dir_name)
day_int += 1
day_int = 1
month_int = 10
while day_int <= 16:
gen_dir_name()
os.mkdir(parent_dir + dir_name)
day_int += 1
print('folders created successfully!')
exit()
but when I run it i receive a NameError...
Traceback (most recent call last):
File "folder_gen.py", line 36, in <module>
gen_dir_name()
File "folder_gen.py", line 32, in gen_dir_name
dir_name = day_str + '-' + month_str + '-' + year_str
NameError: name 'day_str' is not defined
I don't understand why it would be necessary to define day_str (or month_str/year_str) before running the function
I tried to fix it by defining day_str, month_str and year_str in the start, like:
.
.
.
day_int = 16
month_int = 9
year_int = 2020
day_str = str(day_int)
month_str = '0' + str(month_int)
year_str = str(year_int)
.
.
.
But then the program created only one folder (16-09-2020) and exited.
Can someone please explain to me what am I doing wrong?
Upvotes: 0
Views: 113
Reputation: 4981
you have to return each of the created strings in the function, like this example:
def gen_year_str():
return str(year_int)
def gen_dir_name():
dir_name = gen_day_str() + '-' + gen_month_str() + '-' + gen_year_str()
print(dir_name)
# Output:
16-09-2020
......
Upvotes: 1