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
→ Here's my latest YouTube video
→ Get my Python Handbook
→ Get my Python Handbook
→ I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter
→ 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