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

前端 未结 5 1375
陌清茗
陌清茗 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:12

    if os.path.exists(filePath):
        #the file is there
    elif os.access(os.path.dirname(filePath), os.W_OK):
        #the file does not exists but write privileges are given
    else:
        #can not write there
    

    Note that path.exists can fail for more reasons than just the file is not there so you might have to do finer tests like testing if the containing directory exists and so on.


    After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.

    Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.

提交回复
热议问题