howtothings.co.uk
Prompting for an existing path and file name, if invalid, reprompt. - Printable Version

+- howtothings.co.uk (https://www.howtothings.co.uk)
+-- Forum: Computing (https://www.howtothings.co.uk/forumdisplay.php?fid=4)
+--- Forum: Programming Support, Graphic Design and Tutorials (https://www.howtothings.co.uk/forumdisplay.php?fid=14)
+--- Thread: Prompting for an existing path and file name, if invalid, reprompt. (/showthread.php?tid=254)



Prompting for an existing path and file name, if invalid, reprompt. - Mark - 13-07-2010

Prompting for an existing path and file name

Here's a tutorial on checking if a path and file exists, if it doesn't then it'll re-prompt.

Firstly, we need to import the os module.

[code=python]import os[/code]

Next, we'll define our question.

[code=python]def start():
file_path = raw_input ("Enter the file path: ")[/code]

file_path will be equal to the users input, we're going to use os.path.exists to make sure that the path exists.

[code=python]
if os.path.exists(file_path):
print "This file exists"[/code]

Finally we're going to use "if not". If the file doesn't exist, you'll be re-prompted.

[code=python]
if not os.path.exists(file_path):
print "This file doesn't exist"
[/code]


The finished code

[code=python]import os
def start():
file_path = raw_input ("Enter the file path: ")
if os.path.exists(file_path):
print "This file exists"
if not os.path.exists(file_path):
print "This file doesn't exist"
start()
start()[/code]