The method os.path.exists('file.txt')
returns True
if the file 'file.txt'
exists, and False
otherwise. To use it, import the os
module first with import os
. If you want to check if a file exists at a given path, use the standard path notation '/file/at/path/file.txt'
as a prefix.
import os # Check for existing file: print(os.path.exists('main.py')) # True # Check for non-existing file: print(os.path.exists('folder/nonexistent.py')) # False
The web is full of guides that show you “the X most common ways to check if a file exists in Python” (examples: here, here, and here). But when reading over them, I found that it’s hard to extract the precise method—they are far too long and the content is fluffy and lengthy.
If you’re like me, you just want to know the best and most Pythonic way to check if a file exists, right?
In this 2-min tutorial, I’ll give you a to-the-point solution that you can apply right away! So, let’s dive into the precise problem formulation and its most Pythonic way to solve it.
Problem: Given a filename and the path information. Check if a file with the filename exists at a specified path, or not. The return value should be a Boolean value (True
, if the file exists, and False
otherwise).
Example: Say, you’ve got the following filenames as strings, including path information (as string prefix).
filename_1 = 'file-that-exists.txt' # Method returns True filename_2 = 'my/directory/non-existing-file.txt' # Method returns False
You want a method that returns True
for the first filename (the file that exists) and False
for the second filename (the file that doesn’t exist).
Solution: Without further ado, let’s look at the most Pythonic way to check, in your script, if a file exists.
>>> import os >>> os.path.exists('file-that-exists.txt') True >>> os.path.exists('my/directory/non-existing-file.txt') False
You can try this yourself in our interactive code shell:
Exercise: Run the code. What’s the output? Create the non-existing file so that the second method call returns True!
A Pythonic Excursion
You now know how to check if a file exists (and what’s the most Pythonic way of doing so). But there’s a caveat! You actually shouldn’t do it.
The reason is that you probably use your file existence checking mechanism to do something along those lines (only pseudocode):
# PSEUDOCODE: if file_exists(): open_file()
The problem is that your Python program doesn’t have exclusive control of the file on your operating system. You don’t know what’s happening between checking if the file exists and opening the file.
In other words: this method is not thread-safe. Multiple threads may access the same file, which can lead to strange behaviors.
For example, your program may find that the file exists. Another thread may then delete the file, so it doesn’t exist anymore. Then, your program executes the second line open_file()
working on a non-existent file!
To resolve this issue, you should just open the file right away and enclose it in a try/except block. If the file doesn’t exist, Python throws an exception which you catch in your enclosing block.
try: f = open('file.txt') # Do something with file f.close() except FileNotFoundError: print('File does not exist')
This is far better—if you want to avoid any output if the file doesn’t exist, just do nothing in the except statement:
try: f = open('nonexistent_file.py') print(f) f.close() except FileNotFoundError: None
I hope you liked the small tutorial. If you want to improve your Python skills continuously (and for free), check out my email computer science academy (including free cheat sheets)!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.