![]() |
VOOZH | about |
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.
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().
Explanation:
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.
Output:
Empty directory
Explanation:
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.
Output:
The path is either for a file or not valid
Not empty directory
Explanation: