Coding

Python Check if File Exists: pathlib, os.path and try/except

To check if a file exists in Python, use Path("data.csv").is_file() from pathlib, or os.path.isfile("data.csv") from the standard library. Both return True only for an existing regular file; use exists() if a directory should count too.

from pathlib import Path

path = Path("data.csv")
if path.is_file():
    print("found it")
else:
    print("not there")

Every function below returns a plain True or False and does not raise an error for a missing path. That makes them safe to call on any string, but it also means a False can have several causes. The sections after the quick reference cover them.

Which function should you use?

You want to know ifpathlibos.path
a regular file existsPath(p).is_file()os.path.isfile(p)
a directory existsPath(p).is_dir()os.path.isdir(p)
anything exists at the pathPath(p).exists()os.path.exists(p)
a symlink exists, even a broken onePath(p).is_symlink()os.path.lexists(p)

For new code, pathlib is the usual choice: the path is an object, so you can chain .parent, .suffix and / joins. The os.path functions take a string or a path-like object and behave the same way for these checks. The documentation for both modules is linked in the sources below.

exists() vs is_file() vs is_dir()

The Python docs define the three differently:

  • exists() returns True if the path points to an existing file or directory.
  • is_file() returns True if the path points to a regular file.
  • is_dir() returns True if the path points to a directory.

So Path("reports").exists() is True for a folder named reports, and a later open("reports") would fail. If you are going to read the path as a file, test with is_file().

The same applies to os.path: os.path.isfile() returns True for an existing regular file, os.path.isdir() for an existing directory, and both follow symbolic links.

What False can mean

The pathlib documentation says exists(), is_file() and is_dir() return False "if the path is invalid, inaccessible or missing". Those are three different situations that look the same to the caller. If you need to tell them apart, the docs point to Path.stat(), which raises an exception that says which one it was:

from pathlib import Path

try:
    Path("data.csv").stat()
except FileNotFoundError:
    print("missing")
except PermissionError:
    print("exists or not, but we may not look")

The os.path docs give a similar warning for os.path.exists(): on some platforms it may return False if permission is not granted to execute os.stat() on the file, even if the path physically exists.

The behavior for other errors depends on the Python version. The pathlib docs list two changes: since Python 3.8 these methods return False instead of raising for paths containing characters that cannot be represented at the OS level, and since 3.14 they return False instead of raising any OSError. On older versions, some kinds of OSError could still propagate. Check your version with python --version if a check raises where you expected a False.

Broken symbolic links

These functions follow symlinks. For a symlink whose target is missing, the docs give this behavior: os.path.exists() "returns False for broken symbolic links", and for pathlib:

p = Path("link")                  # a symlink whose target is missing
p.exists()                        # False (follows the link)
p.exists(follow_symlinks=False)   # True
p.is_file(), p.is_dir()           # False, False
p.is_symlink()                    # True

This is the example from the pathlib documentation. The follow_symlinks argument of exists() was added in Python 3.12, and the one for is_file() and is_dir() in 3.13. On older versions, use is_symlink() or os.path.lexists(), which returns True for a path that refers to anything, broken symlinks included.

Relative paths depend on the working directory

A relative path such as "data.csv" is resolved against the process's current working directory, not against the folder of your script. If the check returns False for a file you can see, print where Python is looking:

from pathlib import Path

print(Path.cwd())
print(Path("data.csv").resolve())

To anchor a path to the script itself, build it from __file__:

from pathlib import Path

config = Path(__file__).parent / "config.toml"
print(config.is_file())

Check first, or just try to open it?

An existence check can be wrong by the time you act on it. Another process can delete or create the file between your if and your open(). The Python glossary describes this under LBYL ("look before you leap"): in a multi-threaded environment it can introduce a race condition between "the looking" and "the leaping", and the glossary names the EAFP approach as one fix. EAFP means "easier to ask for forgiveness than permission": try the operation and catch the exception.

try:
    with open("data.csv", encoding="utf-8") as f:
        text = f.read()
except FileNotFoundError:
    text = ""
    print("data.csv not found, starting empty")

This version cannot race: either the open succeeds and you have the file, or it fails and you handle that. It also covers cases an is_file() check does not, because it fails for the real reason (permissions, a directory in the way) instead of letting you discover it on the next line. The open() documentation says an OSError is raised if the file cannot be opened; a missing file raises its subclass FileNotFoundError, the exception that Path.unlink() also documents for a missing path.

Use the check when you only need the answer, for example to decide whether to print a hint, skip a step, or choose between two config locations. Use try/except when you are about to read or write the file anyway. For reading line by line after the file is confirmed to be there, see Python read file line by line.

Create a file only if it does not exist

The check-then-create pattern has the same race. Python can do both steps in one call. Mode "x" of open() means "open for exclusive creation, failing if the file already exists":

try:
    with open("new.txt", "x", encoding="utf-8") as f:
        f.write("first line\n")
except FileExistsError:
    print("new.txt already exists, leaving it alone")

FileExistsError is raised when the file is already there, as of Python 3.3. Path.touch() has a similar switch: exist_ok defaults to True, so an existing file just gets its modification time updated. Pass exist_ok=False and it raises FileExistsError instead.

Delete a file only if it exists

Skip the check here too. Path.unlink(missing_ok=True) ignores a missing file, with the same behavior as the POSIX rm -f command. The missing_ok argument was added in Python 3.8. With the default missing_ok=False, a missing path raises FileNotFoundError.

from pathlib import Path

Path("cache.tmp").unlink(missing_ok=True)

unlink() removes a file or a symbolic link. For a directory, the docs say to use Path.rmdir() instead.

If the check gives the wrong answer

  • Printing the full path. Use print(Path("data.csv").resolve()) and look at it in a file manager. A relative path and a different working directory is the most common cause.
  • Trailing spaces or hidden extensions. report.txt and report.txt.txt look the same when Windows hides known extensions. Print repr(name) to see spaces and escapes.
  • Windows backslashes in strings. "C:\new\table.csv" contains \n and \t escapes. Use a raw string, r"C:\new\table.csv", or forward slashes.
  • Permissions. Run Path(p).stat() and read the exception, since exists() reports False for inaccessible paths.

Frequently asked questions

What is the difference between exists() and is_file() in Python?
exists() returns True for any existing path, including directories. is_file() returns True only for a regular file. If your code is about to open the path as a file, use is_file(), because exists() also says True for a folder.
Does os.path.exists() raise an error if the file is missing?
No. It returns False. The os.path documentation also says that on some platforms it may return False when permission is not granted to run os.stat() on the path, even though the path physically exists.
How do I check if a file exists and create it if it does not?
Open it in exclusive creation mode: open(path, 'x'). It creates the file and raises FileExistsError if the file is already there, so the check and the creation happen in one step. Path.touch(exist_ok=False) behaves the same way.
How do I check if a directory exists in Python?
Use Path('folder').is_dir() or os.path.isdir('folder'). Both return True only for an existing directory, and both follow symbolic links.
Why does exists() return False for a file I can see?
Common causes are a relative path resolved against a different working directory than you expect, a broken symbolic link (exists() follows links and returns False when the target is missing), or a path the process has no permission to inspect.

Sources