How to Check if a File or Directory Exists using Python
In this tutorial, you will learn how to check whether a file or folder exists using Python.
TLDR solution
check.py
import os
# file; output: true/false
os.path.isfile("path-to-file/file_name.extension")
# folder/directory
os.path.isdir("path")
Check if File Exists
Let's say, you want to check whether there is a test.csv file on your desktop.
Use isfile to achieves this:
import os
desktop_path = os.path.expanduser("~/Desktop")
check = os.path.isfile(desktop_path + '/test.csv')
print(check)
The output is True or False depending on whether it exists.
Check if Folder Exists
Similarly, you can use isdir to check whether there is a Test folder on your desktop.
import os
desktop_path = os.path.expanduser("~/Desktop")
check = os.path.isdir(desktop_path + '/Test')
print(check)
That's it! You just learned how to check whether a file or folder exists using Python.