Python os.path.exists() Method Tutorial

The Python os.path modules provides useful functions about the pathnames. The os.path.exist() or path.exists() or simply exists() method is used to check if the specified path exists. The specified path can be a file or folder where the os.path.exists() methods only checks if it exists.

os.path.exists() Method Syntax

The os.path.exists() method syntax is like below. If the specified path exists this method returns the boolean value True. If not exists returns the boolean value False.

os.path.exists(PATH)
  • PATH is a path which can be a file, folder, link etc.

Check Path If Exists with os.path.exists() Method

A path or directory can be checked with the os.path.exists() method. We will just povide the path in double quotos like below. In the following example we will check if the “/home/ismail” existst.

import os.path

if os.path.exists("/home/ismail"):
   print("/home/ismail exists")
else:
   print("/home/ismail do NOT exists")

Alternatively we can specify the path as a string variable like below. We will put the path into the string variable named path.

import os.path

path = 
"/home/ismail"

if os.path.exists(path):
   print("/home/ismail exists")
else:
   print("/home/ismail do NOT exists")

Check File If Exists with os.path.exists() Method

The os.path.exists() method can be also used to check if the specified file exists. It is the same with previous examle where we will provide the file name with the file path. In the following example we will check if “/home/ismail/file.txt” exist.

import os.path

if os.path.exists("/home/ismail/file.txt"):
   print("file.txt exists")
else:
   print("file.txt do NOT exists")

Alternatively, we can specify the path as a string variable like below. We will put the path into the string variable named path.

import os.path

path = "/home/ismail/file.txt"

if os.path.exists(path):
   print("file.txt exists")
else:
   print("file.txt do NOT exists")

To make things more strict and check if the specified path is a file and exist we can add os.path.isfile() method like below.

import os.path

path = "/home/ismail/file.txt"

if os.path.exists(path) and os.path.isfile(path):
   print("file.txt exists")

Leave a Comment