Python Forum
Help repeately prompting for directory name if it already exists. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help repeately prompting for directory name if it already exists. (/thread-20262.html)



Help repeately prompting for directory name if it already exists. - hikerguy62 - Aug-02-2019

I'm trying to write some code that will create a directory under an already existing
directory (C:\TIME\SITES). I want to keep asking the user to enter a directory name
if the one they enter already exists. The way it runs now, it prompts for the directory
name twice (the first time it does give the message "Directory already exists". If I enter
the name of a directory that already exists, it prompts me one more time, I enter that same
director name, then the program exits.

How can I get it to keep asking the user to enter a directory name until they enter one that
doesn't already exist?

import os
import shutil

mydir = input("Enter name of directory: ")
os.chdir("C:\\TIM\\SITES\\")
dir_exists = (os.path.exists("C:\\TIM\\SITES\\" + mydir))
try:
	os.mkdir(mydir)
except FileExistsError:
	print("Directory already exists.")
	mydir = input("Enter name of directory: ")



RE: Help repeately prompting for directory name if it already exists. - ichabod801 - Aug-02-2019

You might check out this tutorial on validating input.


RE: Help repeately prompting for directory name if it already exists. - hikerguy62 - Aug-05-2019

I took a look at that example but it wasn't making sense to me, so I found another snippet. I almost have it, but when I run the code below, it's giving me a syntax error and I don't know why:

import os
import shutil

newdir = input("Enter name of directory: ")
dir_exists = (os.path.exists("C:\\TIM\\SITES\\" + newdir))
newdir = ("C:\\TIM\\SITES\\" + newdir)
support_files = ("C:\\TIM\\SITES\\FILES FOR CONFIG BUILD\\")

while dir_exists:
	try:
		newdir = input("Enter name of directory: ")
		dir_exists = (os.path.exists("C:\\TIM\\SITES\\" + newdir))
	else:
		os.mkdir(newdir)
Here's what I see when I run it. I can't figure out what it doesn't like about the else statement:
C:\Users\tomel\Desktop>testing.py
File "C:\Users\tomel\Desktop\testing.py", line 14
else:
^
SyntaxError: invalid syntax


RE: Help repeately prompting for directory name if it already exists. - ichabod801 - Aug-05-2019

You can't use else with try unless you also have an except section. I think you actually want to have that else be except IOError:. That way you make the directory if an error was raised trying to find it.