×

Check if the directory exists in Python

To prevent any error, while loading or editing a file, we first have to check that the directory or the file exists or not. This is also done to prevent overriding the file that already exists. Once the existence is assured, then the file can be loaded and used as required.

The word directory has many meanings in different fields, and in the computing field, it refers to the folder or the file system structure in which the computer files are stored. These files can be of any type, i.e., “.exe”, “.txt”, “zip”, etc.

Therefore, to check the existence of the directory or the file in Python, the following methods can be used:

  • Using the os.path.exists() method
  • Using the os.path.isfile() method
  • Using the os.path.isdir() method
  • Using the pathlib.Path.exists() method

Method 1: Using the “os.path.exists()” method to check the existence of the directory or the file

To use this method, first, we have to import the “OS module”. This module of Python provides multiple functions that are used to interact with the operating system. This module comes in the domain of Python’s standard utility modules. A portable way of using functions that depend on the operating system is provided by this module.

  • os.path is used to manipulate the name for the common path. We use the os.path.exists() method to check whether the path exists or not. This method can also be used to determine whether the given path refers to an open file descriptor or not.

Syntax:

os.path.exists(path)

In this syntax, the path is passed as a parameter to this method. This parameter is used to represent the path of the file. It is generally a string or bytes object that represents a path.

A Boolean value of the bool class is returned by this method. We get the output as True if the directory or the file exists, or else this method will return False as output.

Example:

# Importing the OS module as discussed earlier
importos
 
# Specifying path to pass as a parameter in the method
pth ='/usr/local/bin/'
 
# Checking the existence of the specified path
Exst =os.path.exists(pth)
print(Exst)
 
# Specifying path to pass as a parameter in the method
pth1='/home/User/Desktop/file.txt'
 
# Checking the existence of the specified path
Exst1=os.path.exists(pth1)
print(Exst1)

Output:

False
False 

Method 2: Using the “os.path.isfile()” method to check the existence of the directory or the file

This method also uses the OS module to perform this specified task. In Python os.path.isfile method is used to verify whether the specified path does exist as a regular file or not.

Syntax:

os.path.isfile(path)

In this syntax, the same as the first method, the path is passed as a parameter to this method. This parameter is used to represent the path of the file. It is generally a string or bytes object that represents a path.

A Boolean value of the bool class is returned by this method. We get the output as True if the directory or the file exists, or else this method will return False as output.

Example:

# Importing the OS module as discussed earlier
importos
 
# Specifying path to pass as a parameter in the method
pth ='C:/Users/gfg/Desktop/file.txt'
 
# Checking whether the specified path has an existing file or not
Fle =os.path.isfile(pth)
print(Fle)
 
# Specifying path to pass as a parameter in the method
pth1='/home/User/Desktop/'
 
# Checking whether the specified path has an existing file or not
Fle1=os.path.isfile(pth1)
print(Fle1)

Output:

False
False 

Method 3: Using the “os.path.isdir()” method to check the existence of the directory or the file

We use the os.path.isdir() method to check whether the path specified is an existing directory or not. This method is designed to follow a symbolic link, i.e., this method returns True as output when the provided path is a symbolic link that is pointing to the directory.

Syntax:

os.path.isdir(path)

In this syntax, the same as the first method, the path is passed as a parameter to this method. This parameter is used to represent the path of the file. It is generally a string or bytes object that represents a path.

A Boolean value of the bool class is returned by this method. We get the output as True if the directory or the file exists, or else this method will return False as output.

Example:

# Importing the os.path module
importos.path
  
# Path
pth ='/home/User/Documents/file.txt'
  
# Check whether the 
# specified path is an
# existing directory or not
isdir =os.path.isdir(pth)
print(isdir)


# Path
pth ='/home/User/Documents/'
  
# Check whether the 
# specified path is an
# existing directory or not
isdir =os.path.isdir(pth)
print(isdir)

Output:

False
False 

Method 4: Using the “pathlib.Path.exists()” method to check the existence of the directory or the file

The “pathlib.Path,exists()” method is the final method to check the status of the given directory. To use this method, the path class from the Pathlib module has to be imported. There are multiple classes available in the Pathlib module that provides the paths of the file systems, with appropriate semantics for multiple operating systems.

Python’s standard utility module is the one containing this module. The path class imported from this module is divided into two parts: concrete path and pure path. Computational operations are provided by the pure path, but it does not provide I/O operations. Whereas, the concrete path, inherited from the pure path, provides both, computational operations and I/O operations too.

This method simply checks whether the path provided points to the file or the directory or not.

Syntax:

pathlib.Path.exists(path)

In this syntax, the same as the first method, the path is passed as a parameter to this method. This parameter is used to represent the path of the file. It is generally a string or bytes object that represents a path.

A Boolean value of the bool class is returned by this method. We get the output as True if the directory or the file exists, or else this method will return False as output.

Example:

# Import the Path class from the pathlib module
frompathlib importPathas Pt
 
# Specifying the path to pass as a parameter in the method
pth ='/home/gfg/Desktop'
 
# Instantiate the Path class
objct=Pt(pth)
 
# Checking whether the specified path has an existing directory or not
print(objct.exists())

Output:

False

Related Topics

Standard Scalar in Python

Python is a vast and open-source language that contains many libraries, modules, and functions. These functions in python are reusable codes where we don’t need to type the whole code...

4 minutes read.

Python - Binomial Distribution

Introduction Definition of the Binomial Distribution The method of counting how many instances of a specific event there have been is called the binomial distribution. It will outline the possible outcomes or...

4 minutes read.

Python exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

Syntax of Map function in Python

In this tutorial, we will understand what the map function in Python is meant. Further, we will see the syntax to be used for the same in python language. We...

3 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Python Word Tokenizer

Python Overview Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. Python is an interpreted language...

4 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

STL in Python

Python has many libraries that are very useful and simplify many complex codes. In the same way, STL is also one of the python libraries used for reading and writing...

3 minutes read.

Python Arithmetic Operators

An arithmetic operator is a mathematical operator that is used to operate on two operands. Based on the operator used, action is performed on the operands, and output is delivered. Following...

3 minutes read.

Multiple Linear Regression using Python

Linear Regression: Linear regression is a method that models the relationship between a dependent variable and one or more independent variables; in other terms, that models the relationship between a target...

6 minutes read.

Python Command line Arguments

Python Command line Arguments The command-line argument is used to the change functionality of the program. It's an extra command the programmer can use while launching a program. These commands have many uses...

7 minutes read.

Difference between Module and Package in Python

The main difference between the module and the package in Python is that the module can be a simple file in Python that contains the different functions and collection of...

4 minutes read.

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

Parameter Passing in Python

In Python, when we characterize capabilities with default values for specific boundaries, it is said to have its contentions set as a possibility for the client. Clients can either pass their...

3 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

Python program to find the area of a circle

Python program to find the area of a circle This article will discuss how to find the area of a circle in Python with a given radius. The area of a...

2 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.