Reputation: 25
I wonder if someone can help me with python script:
-If the response is ‘No’ then create a directory for the name(s) in the list.
Quit execution of the script after the directories have been completed.
Before exiting the script inform the user that the directories have been created. -If the response is ‘Yes’ then ask the user the name of the new directory to create.
-Add that name to the list created above
-If the response is anything other than the above two options (i.e. they did not type neither ‘Yes’ nor ‘No’) then repeat the question.
This is what I have done so far, it creates new directory but later I get stuck with ‘Yes’ response:
import os
root_path = r"C:\XYZ"
list_dir = []
userinput1 = raw_input("Please enter the name of new directory:")
list_dir.append(userinput1)
userinput2 = raw_input("Would you like to add another directory? yes/no: ")
if userinput2 == "no":
for list in list_dir:
os.mkdir(os.path.join(root_path,list))
Any help would be much appreciated!
Upvotes: 0
Views: 87
Reputation: 508
I'm not exactly sure if it's important to you that you keep a list of folders that you only create at the very end. Assuming it's not, this should solve your problem:
import os
root = r"C:\XYZ"
while True:
dir_name = raw_input("Please enter the name of new directory: ")
try:
os.mkdir(os.path.join(root, dir_name))
print("Directory '{name}' was created.".format(name=dir_name))
except OSError:
print("Directory '{name}' already exists.".format(name=dir_name))
repeat = raw_input("Would you like to add another directory? yes/no: ")
if repeat.lower() != "yes" and repeat.lower() != "y":
break
If for some reason it is important to only create the list at the very end:
import os
root = r"."
directory_list = []
while True:
directory_name = raw_input("Please enter the name of new directory: ")
directory_list.append(directory_name)
repeat = raw_input("Would you like to add another directory? yes/no: ")
if repeat.lower() != "yes" and repeat.lower() != "y":
break
for directory in directory_list:
try:
os.mkdir(os.path.join(root, directory))
print("Directory '{name}' was created.".format(name=directory))
except OSError:
print("Directory '{name}' already exists.".format(name=directory))
In both cases it will continue if the user inputs any variation of "y", "yes", "Yes", "yEs" and so on, and stops otherwise.
Hope this helps. :)
Upvotes: 1
Reputation: 1957
Try adding a while loop for asking directories:
import os
root_path = r"C:\XYZ"
list_dir = []
while True:
userinput1 = raw_input("Please enter the name of new directory:")
list_dir.append(userinput1)
userinput2 = None
while userinput2 != "yes" and userinput2 != "no":
userinput2 = raw_input("Would you like to add another directory? yes/no: ")
if userinput2 == "no":
break
for directory in list_dir:
os.mkdir(os.path.join(root_path, directory))
First fix if == "no":
to if userinput2 == "no":
Second add a for to loop through the list with directory names and create one by one.
Upvotes: 0