【问题标题】:Check if directory is empty without using os.listdir检查目录是否为空而不使用 os.listdir
【发布时间】:2020-07-30 12:36:24
【问题描述】:

我需要一个函数来检查一个目录是否为空,但它应该尽可能快,因为我将它用于数千个目录,最多可以有 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'))

【问题讨论】:

    标签: python python-3.x winapi ctypes listdir


    【解决方案1】:

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

    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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-21
      • 2018-11-20
      • 1970-01-01
      • 2018-12-23
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多