How do I check whether a file exists without exceptions?

后端 未结 30 1929
北海茫月
北海茫月 2020-11-21 05:07

How do I check if a file exists or not, without using the try statement?

30条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-21 05:27

    Testing for files and folders with os.path.isfile(), os.path.isdir() and os.path.exists()

    Assuming that the "path" is a valid path, this table shows what is returned by each function for files and folders:

    You can also test if a file is a certain type of file using os.path.splitext() to get the extension (if you don't already know it)

    >>> import os
    >>> path = "path to a word document"
    >>> os.path.isfile(path)
    True
    >>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
    True
    

提交回复
热议问题