Check if path is valid in Python

Is there an easy way to check if the path really is? Now the file should not exist, I wonder if it can exist.

my current version is this:

try: f = open(path) except: <path invalid> 

I am considering just checking to see if any of these characters contain a path.

+7
python
Nov 05 '10 at 1:31
source share
2 answers

Trying first is the best way, I recommend doing this.

 try: open(filename, 'w') except OSError: # handle error here 

I believe that you will get an OSError, catch it explicitly and test on the platform you are using it on.

+2
Nov 05 '10 at 1:41
source share
— -

You can also try the following:

 import os if not os.path.exists(file_path): print "Path of the file is Invalid" 
0
Jan 06 '14 at 9:45
source share



All Articles