Python is a widely used general-purpose, high-level programming language. It provides many functionalities and one among them is checking whether a directory is empty or not. This can be achieved by using os module. The OS module in Python provides functions for interacting with the operating system.
OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The
os.path modules include many functions to interact with the file system.
Check if a directory is empty
path (optional): path of the directory
Return Type: This method returns the list of all files and directories in the specified path. The return type of this method is list.
Example #1: If the list returned by
os.listdir() is empty then the directory is empty otherwise not. Below is the implementation.
Example #2: Suppose the path specified in the above code is a path to a text file or is an invalid path, then, in that case, the above code will raise an
OSError. To overcome this error we can use
os.path.isfile() method and
os.path.exists() method. Below is the implementation.
The path is either for a file or not valid Not empty directory
- Check if directory contains file using python
- Python: Check if a File or Directory Exists
- Python - Check if a file or directory exists
- Python | Check if dictionary is empty
- Python | Check whether a list is empty or not
- Python | Check if any String is empty in list
- Python program to check if string is empty or not
- String slicing in Python to check if a string can become empty by recursive deletion
- Create a directory in Python
- Get parent of current directory using Python
- Get directory of current Python script
- Delete a directory or file using Python
- Directory traversal tools in Python
- Change current working directory with Python
- Rename all file names in your directory using Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.