Python os.path.exists() Method

The os.path.exists() method in Python is used to check whether a specified path exists.

This method checks for the existence of files, directories, and even symlinks. For symlinks, it checks the existence of the path the symlink points to.

This method is extremely helpful in file system operations where you need to verify the existence of a path before taking action, such as opening a file, writing to a path, or performing directory operations.

This method works across different platforms (Windows, Linux, macOS).

Syntax

os.path.exists(path)

Parameters

Name Description
path (string) It is the path you want to verify.

Return Value

It returns True if the path argument refers to an existing path (a file, a directory, or a valid symlink). Otherwise, it returns False.

Example 1: Checking if a file exists

Checking if a File exists using Python os.path.exists() method

Here is a file (data.txt) in the current working directory that we will check:

Screenshot of data.txt file inside current working directory

import os

path = "/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt"

if os.path.exists(path):
  print("File exists.")
else:
  print("File does not exist.")

Output

File exists.

Example 2: Checking if a directory exists

Checking if a directory exists

Here is a directory (env) that we will check:

Screenshot of env directory

import os

dir_path = "/Users/krunallathiya/Desktop/Code/pythonenv/env/"

if os.path.exists(dir_path):
  print("Directory exists.")
else:
  print("Directory does not exist.")

Output

Directory exists.

Example 3: Checking for non-existent path

Checking for non-existent path

import os

path = "/Users/krunallathiya/Desktop/Code/pythonenv/env/non_existent.txt"

if os.path.exists(path):
  print("File exists.")
else:
  print("File does not exist.")

Output

File does not exist.

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.