在不使用os.listdir的情况下检查目录是否为空

2024-06-30 15:17:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: import目录looposfindctypeshandlewin32
1条回答
网友
1楼 · 发布于 2024-06-30 15:17:52

您可以使用^{},即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.

相关问题 更多 >