Check whether a path is valid in Python

前端 未结 2 1003
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-15 11:52

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:



        
相关标签:
2条回答
  • 2021-02-15 12:17

    You can also try the below:

    import os  
    if not os.path.exists(file_path):
        print "Path of the file is Invalid"
    
    0 讨论(0)
  • 2021-02-15 12:39

    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 讨论(0)
提交回复
热议问题