How to Check Whether a File Exists Without Exceptions?

Rate this post

Challenge: Given a string '/path/to/'. How to check whether a file exists at '/path/to/', without using the try and except statements for exception handling?

# What You Want!
if exists('/path/to/'):
    ... # Do something

Solution: To check whether a file exists at a given path,

  • Run from pathlib import Path to import the path object,
  • Create a path object with Path('/path/to/'), and
  • Run its .is_file() method that returns True if the file exists and False otherwise.
from pathlib import Path

if Path('/path/to/').is_file():

If the file does exist, you’ll enter the if branch, otherwise you don’t enter it. This method works across all operating systems and modern Python versions.