This short tutorial teaches the simplest way to check if the file exists python and it also extends the tutorial to check if a folder exists.
1. Check If File Exists
First and fore most, in case you want to know how to check if file exists in python, you can import the Path from pathlib and follow the steps below.
In the example below, I use a file that exists on my computer and one that does not:
>>> from pathlib import Path
# this file exists
>>> photo_path = Path("/Users/onestopdataanalysis/photos/photo.png")
# this does not file exists
>>> photo_path_fake = Path("/Users/onestopdataanalysis/photos/photo_fake.png")
# confirms that files exist
>>> photo_path.exists()
# confirms that does files exist
>>> photo_path_fake.exists()
This should return
# the first file exists
True
# the second file is fake
False
2. Check If Folder Exists
Next, you can also use Path to check if folder exists – in python Path can be used to check if it is a directory. See below.
In the example below, I use a folder/directory that exists on my machine and one that does not:
>>> from pathlib import Path
# this directory exists
>>> real_dir = Path("/Users/onestopdataanalysis/Desktop/exists/photos/")
# this does not exists
>>> real_dir_fake = Path("/Users/onestopdataanalysis/Desktop/exists/photos_fake/")
# confirms it is a directory
>>> real_dir.is_dir()
# confirms it is not a directory
>>> real_dir_fake.is_dir()
Which should print
# the first folder exists
True
# the second folder is fake
False
More Resources
Here are three of my favorite Python Books in case you want to learn more about it.
- Python Cookbook, Third Edition by David Beazley and Brian K. Jones
- Learning Python, 5th Edition Fifth Edition by Mark Lutz
- Python Pocket Reference: Python In Your Pocket by Mark Lutz