首页 > 解决方案 > 检查目录是否为空而不使用 os.listdir

问题描述

我需要一个函数来检查一个目录是否为空,但它应该尽可能快,因为我将它用于数千个目录,最多可以有 100k 个文件。我实现了下一个,但看起来 python3 中的 kernel32 模块有问题(我OSError: exception: access violation writing 0xFFFFFFFFCE4A9500从第一次调用就开始使用 FindNextFileW)

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'))

标签: pythonpython-3.xwinapictypeslistdir

解决方案


您可以使用os.scandir的迭代器版本listdir,并在“迭代”第一个条目时简单地返回,如下所示:

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.

推荐阅读