How do I check whether a file exists without exceptions?

后端 未结 30 1951
北海茫月
北海茫月 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:28

    Unlike isfile(), exists() will return True for directories. So depending on if you want only plain files or also directories, you'll use isfile() or exists(). Here is some simple REPL output:

    >>> os.path.isfile("/etc/password.txt")
    True
    >>> os.path.isfile("/etc")
    False
    >>> os.path.isfile("/does/not/exist")
    False
    >>> os.path.exists("/etc/password.txt")
    True
    >>> os.path.exists("/etc")
    True
    >>> os.path.exists("/does/not/exist")
    False
    

提交回复
热议问题