Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a path is valid in Python

Tags:

python

Is there any easy way to check whether a path is valid? The file doesn't have to exist now, I'm wondering if it could exist.

my current version is this:

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

I'm considering simply checking whether the path contains any of these characters.

like image 424
dutt Avatar asked Nov 05 '10 01:11

dutt


People also ask

How do you check if a path does not exist in Python?

exists() is used to determine whether or not the supplied path exists. The os. path. exists() method produces a boolean value that is either True or False depending on whether or not the route exists.

What is path () in Python?

path module is a very extensively used module that is handy when processing files from different places in the system. It is used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters.

What is a valid path name?

By "pathname validity," we mean the syntactic correctness of a pathname with respect to the root filesystem of the current system – regardless of whether that path or parent directories thereof physically exist.


2 Answers

You can also try the below:

import os  
if not os.path.exists(file_path):
    print "Path of the file is Invalid"
like image 76
Vidz Avatar answered Nov 09 '22 21:11

Vidz


Attempting it first is the best way, I recommend doing that.

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

I believe you'll get OSError, catch that explicitly, and test on the platform you're using this on.

like image 21
Jerub Avatar answered Nov 09 '22 19:11

Jerub