Search code examples
pythonpython-3.xwinapictypeslistdir

Check if directory is empty without using os.listdir


I need a function to check if a directory is empty, but it should be as fast as possible, because I use it for thousands of directories that can have up to 100k files. I implemented the next one, but it looks like something is wrong with kernel32 module in python3 (I get OSError: exception: access violation writing 0xFFFFFFFFCE4A9500 on FindNextFileW, right from the first call)

import os
import ctypes
from ctypes.wintypes import WIN32_FIND_DATAW

def is_empty(fpath):
    ret = True
    loop = True
    fpath = os.path.join(fpath, '*')
    wfd = WIN32_FIND_DATAW()
    handle = ctypes.windll.kernel32.FindFirstFileW(fpath, ctypes.byref(wfd))
    if handle == -1:
        return ret
    while loop:
        if wfd.cFileName not in ('.', '..'):
            ret = False
            break
        loop = ctypes.windll.kernel32.FindNextFileW(handle, ctypes.byref(wfd))
    ctypes.windll.kernel32.FindClose(handle)
    return ret

print(is_empty(r'C:\\Users'))

Solution

  • You can use os.scandir, the iterator version of listdir, and simply return upon "iterating" the first entry, like this:

    import os
    
    def is_empty(path):
        with os.scandir(path) as scanner:
            for entry in scanner: # this loop will have maximum 1 iteration
                return False # found file, not empty.
        return True # if we reached here, then empty.