Check whether a path is valid in Python without creating a file at the path's target

前端 未结 5 1407
陌清茗
陌清茗 2020-11-29 16:32

I have a path (including directory and file name).
I need to test if the file-name is a valid, e.g. if the file-system will allow me to create a file with such a name.

5条回答
  •  孤街浪徒
    2020-11-29 17:30

    open(filename,'r')   #2nd argument is r and not w
    

    will open the file or give an error if it doesn't exist. If there's an error, then you can try to write to the path, if you can't then you get a second error

    try:
        open(filename,'r')
        return True
    except IOError:
        try:
            open(filename, 'w')
            return True
        except IOError:
            return False
    

    Also have a look here about permissions on windows

提交回复
热议问题