Suppose I have a directory C:/Test
that is either empty or contains more than 2000000 files, all with the same extension (e.g. *.txt
).
How can I use Python to determine if the directory is empty WITHOUT the enumeration of files?
Suppose I have a directory C:/Test
that is either empty or contains more than 2000000 files, all with the same extension (e.g. *.txt
).
How can I use Python to determine if the directory is empty WITHOUT the enumeration of files?
I realise this is quite an old question but I found this as I was looking to do a similar thing and I found os.scandir to be useful in combination with any(). scandir() will return an iterator of entries in a directory rather than a list. any() can evaluate if the iterator is non-empty.
for _ in os.scandir(path):
print('not empty')
break
or
if any(os.scandir(path)):
print('not empty')
Is this what you're looking for?
import os
if not os.listdir('C:/Test'):
print "empty"
edit: test run
for x in range(0, 3000000):
open(str(x), 'a').close()
print not os.listdir('.')
output: False
def isempty(dirpath):
""" Check the given directory path to determine if it is empty. The special entries '.' and '..' are not considered.
:param dirpath: A directory path which may be a PathLike object
:return: True if the directory is empty, else False
:raises FileNotFoundError: If the directory does not exist
"""
import os
try:
with os.scandir(dirpath) as it:
for inode in it:
raise FileExistsError()
except FileExistsError:
return False
else:
return True
The above Python code uses scandir to efficiently check for an empty directory and will correctly close the scandir iterator in order to not cause a ResourceWarning to be emitted in the scandir destructor.