开发者

Check whether a path is valid in 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 i开发者_StackOverflow社区t 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.


You can also try the below:

import os  
if not os.path.exists(file_path):
    print "Path of the file is Invalid"


From python 3.4, to check if path is valid, you can also use pathlib module to do this:

from pathlib import Path

try:
    Path(file_path).resolve()
    exist = True
except (OSError, RuntimeError):
    exist = False


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜