×

Check whether dir is empty or not in python

Python: Check if a directory is empty

In this tutorial, we will study how to check whether the director (dir) is empty or not in the python programming language. First of all, we will understand the background of Python. Further, we will focus on understanding the meaning of the directory. Then, we will proceed further to our main topic. We will understand our topic through two examples.

Background

As we know of the nature of python, it is an extensively used, all-purpose, high-level programming language. The speciality of this language is user-friendliness. It aims to lower the burden on programmers by providing several built-in functions and modules inspecting whether a directory is vacant or not is one of its popular functionalities. The vacancy of a directory can be achieved by means of the os module available here. For the purpose of interaction with the operating system, The OS module in Python delivers functions which serve our purpose. The OS module belongs to Python’s standard utility modules. This module offers a transportable method of using the functions that are not independent of the operating system. The modules such as os and os.path comprise numerous functions related to the file system.

What is directory

Directories are a method used for managing the files on a computer. It includes storing, organizing, and separating files. The directory without a parent or a guardian is a root directory. The path defines the route to reach and fetch the file. The path consists of a mixture of names of a directory, and names of a folder separated by slashes ( / ) and colon( : ), and this results in the route of a file in the system.

Example of a directory-

/home/javatpoint/Desktop/jtp
/home/javtpoint/Desktop

Checking whether the directory is empty or not

To inspect if a directory is vacant or not, the methods named os.listdir() are taken into account. This method of the os module is used to fetch the list of all the documents and directories in the stated directory.

Syntax:

os.listdir(path)

Let us see the details of the Parameters used above:

  • path (optional): It refers to the path of the directory
  • Return Type: It refers to the method which returns the list of all documents and directories in the stated path. It returns the output in the list.

Illustrations:

1.The directory is empty if the list given out by os.listdir() is empty; otherwise, it is filled. Below is the implementation to understand it.

# Python program to check if
# the directory stated is empty or full.




import os


# giving the path of the directory
path = "D:/Pycharm projects/tutorials and example/Sakshi"


# Getting the list of directories
dir = os.listdir(path)


# Checking whether the list is empty or not
if len(dir) == 0:
  print("The directory is empty ")
else:
  print("The directory is not empty ")

Output:

Python: Check if a directory is empty

1.The code written below is to overcome the issue of OSError, which can be encountered in the above program case. For example, if the path stated in the above code is a pathway to a text file or is a wrong path, then, in that circumstance, the above code will raise an OSError. So, to overcome this problem, following two methods, namely os. path.isfile() method and os.path.exists() method are taken into account. Below is the implementation to understand the stated concept.

# Python program to check if
# the directory stated below is empty or filled.




import os


# The function to verify whether the path stated
# is a valid directory or not.


def isEmpty(path):
  if os.path.exists(path) and not os.path.isfile(path):


    # Checking whether the directory is empty or full


    if not os.listdir(path):
      print ("The directory is empty")
    else:
      print ("The directory is not empty ")
  else:
    print ("The path is either for a file or is invalid")




# The path of a file
path = "E:/monthly report/tutorials and example/Sakshi/jtp.txt"
isEmpty(path)
print ()


# valid path
path = "E:/monthly report /tutorials and example/Sakshi/"
isEmpty(path)

Output:

Python: Check if a directory is empty

Summary:

In this tutorial, we firstly understood the meaning of the directory and moved to our main topic, which is how to check whether the directory is empty or not. For this, we saw two snippets of code. The first one is a simple code, which could even result in an exception, while the second one overcomes the error possible in the first code.


Related Topics

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

Write Dictionary to CSV 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...

4 minutes read.

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Create First GUI Application 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...

6 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Convert List to Array in Python

What is List in Python? In Python, a list is a built-in data structure that stores a collection of items. The items in a list can be of any data type,...

3 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Arguments and parameters in Python

Generally, there is a misunderstanding that parameters and arguments, both are the same. But, as a programmer, you need to understand the difference between these two. Parameters: While defining a function, we...

5 minutes read.

How to Read html page in python

Html is a Hyper Text Markup language is a standard language used for creating webpages. HTML is the name of the language used to describe the construction of Web pages....

4 minutes read.

Accessing Key-value in Dictionary in Python

A Python word reference is an assortment of key-esteem matches where each key is related to worth. Worth in the key-esteem pair can be a number, a string, a rundown,...

5 minutes read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

Python Set union() method

Python Set union() method The set.union() method in Python returns a set that contains all items from the original set and all items from the specified sets. Syntax set.union(set1, set2...) Parameter set1- This parameter represents the first set...

2 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Python input() function

Python input() function The input() function in Python reads a line from input and converts it to a string (stripping a trailing newline). Syntax input([prompt]) Parameter prompt: This function represents a string, depicting a default...

1 minute read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

Number Pattern Programs in Python

Learning Python is very easy, and it understands in better way compared to other programming languages. One of the many reasons why it has emerged as the most widely used...

4 minutes read.

Python bool()

Python bool() class The bool() class in Python returns the boolean value for the specified object. Syntax class bool([x]) Parameter object: This parameter represents the object, like String, List, Number etc. Return It will always return True, except...

1 minute read.

Python Set isdisjoint() method

Python Set isdisjoint() method The set.isdisjoint() method in Python returns a boolean value True if two sets are disjoint sets ( i.e. none of the elements are present in both sets), otherwise it returns...

1 minute read.