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.
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.
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.
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.
You can also try the below:
import os
if not os.path.exists(file_path):
print "Path of the file is Invalid"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With