Check if a File or Directory Exists using Python

You can use the following templates to check if a file or a directory exists using Python:

(1) Check if a file exists using os.path.isfile:

import os.path

file_exists = os.path.isfile(r"path where the file is stored\file_name.file_extension")

print(file_exists)

(2) Check if a directory exists using os.path.isdir:

import os.path

directory_exists = os.path.isdir(r"path of directory")

print(directory_exists)

Steps to Check if a File Exists using Python

Step 1: Capture the path where your file is stored

To start, capture the path where your file is supposed to be stored.

For example, let’s say that a text file called ‘New_Products‘ is stored under the following path:

C:\Users\Ron\Desktop\Test\New_Products.txt

Where the file name is ‘New_Products‘ and the file extension is ‘.txt‘.

Step 2: Check if the file exists using os.path.isfile

You can use the following template in order to check if a file exists:

import os.path

file_exists = os.path.isfile(r"path where the file is stored\file_name.file_extension")

print(file_exists)

Here is the complete code for our example (don’t forget to place the ‘r‘ character before the path name to avoid errors with the path):

import os.path

file_exists = os.path.isfile(r"C:\Users\Ron\Desktop\Test\New_Products.txt")

print(file_exists)

As you can see, the value is ‘True‘ which means that the file exists for the path specified:

True

Additional Resources

You may check the os.path module to read more about os.path.isfile.

Leave a Comment