Categories
file file-exists python

How do I check whether a file exists without exceptions?

6698

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

2

  • 15

    To check whether a Path object exists independently of whether is it a file or directory, use my_path.exists().

    Aug 6, 2020 at 19:40

  • 1

    my_path.exists() is not sufficient. my_path.is_file() will tell you if its a file (could be good for reading). But if you want to create the file, you also have to check exists so exclude directories or other non-file things in the file system that will cause the fail.

    – tdelaney

    Sep 15, 2021 at 6:56

2474

Use os.path.exists to check both files and directories:

import os.path
os.path.exists(file_path)

Use os.path.isfile to check only files (note: follows symlinks):

os.path.isfile(file_path)

0

    1157

    +50

    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
    

    0