I work on a windows machine and want to check if a directory on a network path is empty.
The first thing that came to mind was calling os.listdir()
and see if it has length 0.
i.e
def dir_empty(dir_path):
return len(os.listdir(dir_path)) == 0
Because this is a network path where I do not always have good connectivity and because a folder can potentially contain thousands of files, this is a very slow solution. Is there a better one?
The fastest solution I found so far:
def dir_empty(dir_path):
return not any((True for _ in os.scandir(dir_path)))
Or, as proposed in the comments below:
def dir_empty(dir_path):
return not next(os.scandir(dir_path), None)
On the slow network I was working on this took seconds instead of minutes (minutes for the os.listdir() version). This seems to be faster, as the any statement only evaluates the first True statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With