11

Possible Duplicate:
How do I check if a file exists using Python?

I am a beginner at Python. I have a bit of code that I want to handle in a way if that someone was to enter an invalid path that does not exist like Z:\ instead of C:\ I want it to raise some sort of error. I know how to go about doing it, I just don't know how to check if it will be invalid. How can I make my code check if that drive or path exists on this PC before it creates the path, is there a way to do that in python?

file_path = input("\nEnter the absolute path for your file: ")
Ryan M
  • 18,333
  • 31
  • 67
  • 74
thechrishaddad
  • 6,523
  • 7
  • 27
  • 33
  • Why the downvote without a comment? This is a good question from a person just starting out. It raises the fundamental ethos of whether to test or except – Jay M Sep 25 '12 at 13:09
  • 1
    @JasonMorgan This question shows little own research effort. Title and tags are not directly related to the actual question. The body formatting doesn't really make it easy to recognize the actual question either. I can understand how someone could dare to downvote this. – moooeeeep Sep 25 '12 at 13:12

2 Answers2

7

The Pythonic way of handling this is to "ask forgiveness, not permission": just try to perform whatever operation you were going to on the path you get (like opening files) and let the functions you're calling raise the appropriate exception for you. Then use exception handling to make the error messages more user friendly.

That way, you'll get all the checks done just in time. Checking beforehand is unreliable; what if you check whether a file exists, just before some other process deletes it?

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • Or you can the input statement into a loop and then use os.path.exists(), but the answer is correct in a more Pythonic way. – Jay M Sep 25 '12 at 13:06
  • @JasonMorgan: it's even a more robust and secure way. See expanded answer for rationale. – Fred Foo Sep 25 '12 at 13:09
2

I guess you are looking for something like this. You can use try and except to test if things will work or not. You can also handle specific exceptions under the except block. (I'm sure urlopen will return one when it fails)

from urllib import urlopen
website_path = raw_input("\nEnter the absolute path for your website: ")
try:
    content = urlopen(website_path).read()
    print "Success, I was able to open: ", website_path 
except:
    print "Error, Unable to open: " , website_path
joeButler
  • 1,643
  • 1
  • 20
  • 41