python - 检查目录是否为空而不使用 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'))
解决方案
您可以使用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.
推荐阅读
- javascript - 只能在更新后的第二次迭代中拉/调用 React Native 状态
- javascript - 使用 Jquery 提交登录
- python - 将 Matlab 结构转换为 python/numpy
- android-studio - 如何从 RecyclerView Retrofit Kotlin Android Studio 中搜索数据?
- javascript - DropzoneJS - 事件中的异步任务未按预期工作
- laravel - 如何在 laravel eloquent 模型中优化以下查询?
- python - Python pyplot - 在条形图标签之间绘制圆弧图
- python-3.x - 创建活动时出现 Google 日历 API 400 错误
- pandas - 为什么 pandas.melt 会弄乱我的 dtypes?
- mysql - 如何仅使用时间戳字段的日期部分更新日期字段?