howtothings.co.uk

Full Version: Prompting for an existing path and file name, if invalid, reprompt.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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]