Checking whether a directory is empty is a common file-system operation in Python. The os module provides multiple ways to do this. The most efficient approach is using os.scandir(), which scans entries one by one without loading the entire directory into memory. Alternatively, os.listdir() can also be used when simplicity is preferred.
1. Using os.scandir()
os.scandir() returns an iterator, so Python stops as soon as it finds the first file or subdirectory. This makes it faster and more memory-efficient than os.listdir().
import os
path = r"D:/Pycharm projects/GeeksforGeeks/Nikhil"
empty = True
for _ in os.scandir(path):
empty = False
break
if empty:
print("Empty directory")
else:
print("Not empty directory")
Explanation:
- os.scandir(path) creates an iterator over directory entries.
- Loop breaks immediately when an item is found. If the loop never runs, the directory is empty.
- A boolean (empty) tracks whether any entry was discovered.
2. Using os.listdir()
os.listdir() returns a list of all files and directories inside the given path.
Example 1: If the list returned by os.listdir() is empty then the directory is empty otherwise not.
import os
# path of the directory
path = r"D:/Pycharm projects/GeeksforGeeks/Nikhil"
# Getting the list of directories
dir = os.listdir(path)
# Checking if the list is empty or not
if len(dir) == 0:
print("Empty directory")
else:
print("Not empty directory")
Output:
Empty directory
Explanation:
- os.listdir(path) loads all files/subdirectories into a list.
- len(dir) == 0 means the directory contains no entrie
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.
import os
# path to a file
path = "D:/Pycharm projects/GeeksforGeeks/Nikhil/gfg.txt"
if os.path.exists(path) and not os.path.isfile(path):
if not os.listdir(path):
print("Empty directory")
else:
print("Not empty directory")
else:
print("The path is either for a file or not valid")
print()
# valid directory path
path = "D:/Pycharm projects/GeeksforGeeks/Nikhil/"
if os.path.exists(path) and not os.path.isfile(path):
if not os.listdir(path):
print("Empty directory")
else:
print("Not empty directory")
else:
print("The path is either for a file or not va
Output:
The path is either for a file or not valid
Not empty directory
Explanation:
- os.path.exists(path) checks whether the path exists.
- os.path.isfile(path) ensures the path is not pointing to a file.
- Only valid directory paths are checked with os.listdir().