×

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

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

How to set up a proxy using selenium in python

What is Proxy? A proxy acts as a middleman between user requests and server responses. The main purposes of proxies are to protect user privacy and encapsulate data between various interactive...

3 minutes read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.

Python List extend() method

Python List extend() method The list.extend() method extends the list by appending all the items from the iterable. Syntax list.extend(iterable) Parameter iterable: It is a required parameter which represents any iterable unlike list, set, tuple, etc. Example 1 # Python...

1 minute read.

Number pattern in Python

Number pattern in Python: This article explains how to print number patterns in Python. The FOR loop, while loop, and range() functions are used in the following Python programs to...

4 minutes read.

Enumerate() Function in Python

The enumerate() function in Python is used to convert a data collection object into an enumerate object. It returns an object that contains a counter as a key for each...

3 minutes read.

ER diagram of the Bank Management System in python

What is an ER diagram? The full form of the ER diagram is the Entity Relationship diagram. This diagram is used in database management systems to have a rough idea of...

3 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Compound Interest GUI Calculator using PyQt5 in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

6 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Conditional Statements in python

In this article, we will learn about conditional statements and how to apply conditional statements in Python. A decision-making statement is another name for a conditional statement. Decision-making is an important...

5 minutes read.

Exit program in python

Exit program in python The quit(), exit(), and sys.exit() functions have almost the same functionality as they raise the SystemExit exception by which the Python interpreter exit and no stack traceback...

2 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.

Augmented reality in python

In this article, we shall learn about augmented reality in python. Augmented reality is a technology that captures the world around you and adds virtual content or objects on top of...

3 minutes read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

4 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Python | Read csv using pandas.read_csv()

Python is an excellent language for performing information analysis, owing to the fantastic biological system of information-driven python packages. Pandas is one of those packages that make taking in and...

4 minutes read.

Python Dictionary values() method

Python Dictionary values() method The dictionary.values() method in Python returns a view object that displays a list of all the values in the specified dictionary. Syntax dictionary.values() Parameter NA Return This method returns a view object. The...

1 minute read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.