How to Check If a File Exists Without Exceptions in Python

Exploring with os and the isFile function

Jonathan Hsu
Oct 21 · 2 min read
Photo by Brett Jordan on Unsplash

When performing actions contingent on successful execution, variations of try/except statements are used to capture exceptions and respond accordingly. The basic premise here is leaping before looking, knowing that you have plans in place for errant actions. But what if you want to look before you leap? Specifically when working with files?

All of our solutions will use the os library and use the isfile() method, which returns True or False. The remainder is dictated by where the file to be checked exists relative to the executing file.


Guidelines for Exploration

Asking yourself the following questions will ensure a thorough search.

Is the file in the same directory?

To check for a file that exists within the same directory as the executing file, simply pass the file name to the method as a string.

Is the file in a subdirectory?

If the file you are checking for is in a subdirectory of the executing file, then pass the relative path to the method.

Is the file in a different directory?

If the file is in a completely different directory or you don’t want to be restricted to a relative path, pass the absolute path to the method.

Better Programming

Advice for programmers.

Jonathan Hsu

Written by

I’m a black belt problem-solver (literally). I enjoy the taking on new challenges, building skills, and sharing what I’ve learned. 🥋

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade