Check if folders and files exist in Python

The methods to check if folders and files exist in Python 3 are:

  • The isdir function to check if folders exist
  • The isfile function to check if files exist.

» More Python Examples

Here is a code example:

import os

# geekole.com

if os.path.isdir('/home/geekole/Documents/python/test_files/'):
    print('The folder exists.');
else:
    print('The folder does not exist.');

if os.path.isfile('/home/geekole/Documents/python/files/file.txt'):
    print('The file exists.');
else:
    print('The file does not exists.');

In our example, the folder “test_files” does not exist and if “file.txt” exists, the result is as follows:

Folders and files exist in Python

Note: The examples are edited and run with the help of Visual Studio Code.

We hope this example of Check if folders and files exist in Python will help you.