Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python if statement error handling [duplicate]

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: ")
like image 675
thechrishaddad Avatar asked Sep 25 '12 13:09

thechrishaddad


1 Answers

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?

like image 85
Fred Foo Avatar answered Oct 14 '22 16:10

Fred Foo