• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Prompting for an existing path and file name, if invalid, reprompt.
#1
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]
  Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Prompting users for input, then verifying what they've inputted Mark 0 4,414 13-07-2010, 01:22 PM
Last Post: Mark

Forum Jump: