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

Is the file in the same directory?

os.path.isfile("file_in_same_dir.py")

Is the file in a subdirectory?

os.path.isfile("images/logo.png")

Is the file in a different directory?

os.path.isfile("/var/www/html/blog/images/logo.png")

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