How to Check if a File Exists in Python
When working with files in Python, you’ll often need to check if a file exists before you do anything else with it, such as reading from or writing to it. Luckily, the Python standard library makes this a piece of cake.
Use pathlib.Path.exists(path) to check for files and directories
from pathlib import Path
path_exists = Path.exists("home/dir/file.txt")
if path_exists:
print("found it!")
else:
print("not found :(")
Notice that path_exists will be True whether this is a file or a directory, it’s only checking if the path exists.
Note: On older versions of Python you may not have access to the pathlib module. If that’s the case, you can use os.path.exists().
from os.path import exists
path_exists = exists("home/dir/file.txt")
if path_exists:
print("found it!")
else:
print("not found :(")
Use pathlib.Path(path).is_file() to check for only files
from pathlib import Path
file_exists = Path.is_file("home/dir/file.txt")
if file_exists:
print("found it!")
else:
print("not found :(")
Use pathlib.Path(path).is_dir() to check for only directories
from pathlib import Path
dir_exists = Path.is_dir("home/dir")
if dir_exists:
print("found it!")
else:
print("not found :(")
Use pathlib.Path(path).is_symlink() to check for only symlinks
A symlink is a path that points to, or aliases another path in a filesystem.
from pathlib import Path
symlink_exists = Path.is_dir("home/dir/some_symlink")
if symlink_exists:
print("found it!")
else:
print("not found :(")
Related Articles
Python vs C++: The Best Language To Learn For You
Nov 17, 2021 by Meghan Reichenbach
It’s either a blessing or a curse when choosing to learn Python or C++ because there couldn’t be two more opposing languages to compare.
Python vs PHP: 9 Critical Differences Examined
Nov 05, 2021 by Zulie Rane - Data analysis and computer science techincal author
PHP famously claims to be the backend programming language for just under 80% of the Internet. However, if you look at the popularity rankings of programming languages, Python is consistently far ahead of PHP. How can that be? Both languages can be used for backend web development, and PHP was even specifically made for web development.
Ruby vs Python: 10 Questions to Ask Before You Choose
Oct 25, 2021 by Zulie Rane - Data analysis and computer science techincal author
A ruby is a beautiful red gemstone; a python is a beautiful green snake. Aside from that, they’re both very popular programming languages. They’re popular for different reasons, and they’re good at different things. Before you choose between Ruby vs. Python, make sure you ask yourself these 10 questions.
The 7 Best Ways to Learn Python
Oct 12, 2021 by Zulie Rane - Data analysis and computer science techincal author
Everyone wants to know the best way to learn to code Python nowadays. It’s a great language, as I’ve written about before, with great career prospects and tons of useful features.