Skip to content

Python, how to check if a file or directory exists

The os.path.exists() method provided by the os standard library module returns True if a file exists, and False if not.

Here is how to use it:

import os

filename = '/Users/flavio/test.txt'

exists = os.path.exists(filename)

print(exists) # True

→ Get my Python Handbook
→ Get my Python Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list