Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest way to check whether a directory is empty in Python

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?

like image 524
rob Avatar asked Dec 11 '22 02:12

rob


1 Answers

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.

like image 192
rob Avatar answered Dec 12 '22 14:12

rob