×

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

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

Python String rfind() method

The string. rfind() method in Python returns the highest index in the string if the substring sub is found else it returns -1 if the substring is not found. Syntax string.rfind(sub [,start [,end]]) Parameter sub: This parameter...

2 minutes read.

Python object()

Python object() class The object class in Python is a base for all classes. It returns a new featureless object. Syntax class object Parameter NA Return It returns a new featureless object. Example 1 # Python program explaining # the object()...

1 minute read.

What does base case mean in recursion

Base cases and recursive stages are used to define recursive functions. In a primary subject, we compute the outcome right away, given the function call's arguments. In a recursive step, we...

4 minutes read.

Fsolve in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python try catch exception

The try-except proclamation can deal with exceptions. Exceptions might happen when you run a program. Exceptions are blunders that occur during the execution of the program. Python won't educate you regarding...

3 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Python vs R

Python: - Python is a popular high-level, general-purpose programming language. Python (the most recent version is Python 3) is a programming language used in the software industry for website development, machine...

3 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

Python Key Error

What is an Error? Errors are nothing but problems in the program which occur in a program code, and this will stop the execution of the program. It is also called...

6 minutes read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Tuple in Python

Tuples Tuples are the same as the list but as we know that lists are mutable means we can change the data from it. In the tuple we cannot change the...

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

How to develop a game in python

Fun always makes a task interesting and easy to execute. Learning in the same theoretical way at some point reaches the boring spot. In this article, using some Python knowledge,...

13 minutes read.

Python Keywords

If you are trying to learn a programming language, you need to have a basic idea of "What are keywords" and "How they are used". You can learn about keywords in...

7 minutes read.

Python Modulo

For basic calculations, Python provides operators. Python supports a broad range of Arithmetic Operators to do arithmetic, as given below: +Addition*Multiplication-Subtraction/Division//Floor division**Exponentiation%Remainder/Modulus As you can see, one of these basic arithmetic operators...

8 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Python Data Visualization

In this tutorial, we will understand what data visualization means in python. Further, we will see different methods of visualizing data in python. Data visualization In a non-technical language, it is a...

4 minutes read.