You can use these two methods from the os module.
First option:
import os
if len(os.listdir('/your/path')) == 0:
print("Directory is empty")
else:
print("Directory is not empty")
Second option (as an empty list evaluates to False
in Python):
import os
if not os.listdir('/your/path'):
print("Directory is empty")
else:
print("Directory is not empty")
However, the os.listdir()
can throw an exception, for example when the given path does not exist. Therefore, you need to cover this.
import os
dir_name = '/your/path'
if os.path.isdir(dir_name):
if not os.listdir(dir_name):
print("Directory is empty")
else:
print("Directory is not empty")
else:
print("Given directory doesn't exist")
I hope it will be helpful for you.
Note that os.listdir(dir_name)
does not include the special entries '.' and '..' even if they are present in the directory.
Source: http://web.archive.org/web/20180531030548/http://thispointer.com/python-how-to-check-if-a-directory-is-empty
print os.listdir(downloadsFolder)
?