One of Python’s many features is the ability to determine whether or not a directory is empty. The os module can be used to accomplish this. In Python, the OS module has functions for communicating with the operating system. Python’s basic utility modules include OS. This module allows you to use operating system-dependent features on the go. Many functions to communicate with the file system are included in the os and os.path modules.
A directory, also known as a folder, is a grouping of files and subdirectories. The os module in Python contains many useful methods for working with directories (and files as well).
Given a directory the task is to check whether the given _directory is empty or not
Check if a Directory is Empty
The os module in Python has a feature that returns a list of files or folders in a directory.
os.listdir(path='.')
It gives you a list of all the files and subdirectories in the direction you specified.
There are several ways to check whether the directory is empty or not some of them are:
Method #1:Using len() function
The directory is empty if the returned list is empty or has a size of 0.
We can find size using len() function.
If the given then it will print given_directory is empty else given_directory is not empty
Below is the implementation:
# checking if the given directory is empty or not if len(os.listdir('/home/btechgeeks/posts')) == 0: print("given_directory is empty") else: print("given_directory is not empty")
Output:
given_directory is empty
Method #2:Using not operator
If not of given path is true then it will print given_directory is empty
else given_directory is not empty.
Below is the implementation:
# checking if the given directory is empty or not if not os.listdir('/home/btechgeeks/posts'): print("given_directory is empty") else: print("given_directory is not empty")
Output:
given_directory is empty
In exceptional cases, check to see if a directory is empty
There may be times when os.listdir() throws an exception. As an example,
- If the specified path does not exist.
- If the given path exists, but it is not a directory.
In both cases, os.listdir() will return an error, so we must check this first before calling os.listdir().
Below is the implementation:
# checking if the given directory is empty or not # given directory given_directory = '/home/btechgeeks/posts' if os.path.exists(given_directory) and os.path.isdir(given_directory): if not os.listdir(): print("given_directory is empty") else: print("given_directory is not empty") else: print("given_directory doesn't exists')
Output:
given_directory is empty
Related Programs:
- python three ways to check if a file is empty
- pandas 4 ways to check if a dataframe is empty in python
- how to check if a file or directory or link exists in python
- python how to check if a key exists in dictionary
- python check if a list is empty or not
- python program to check if a string is palindrome or not
- python program to check if a string is a pangram or not