我想递归地遍历一个目录,但是我希望python如果遇到目录中包含100个以上文件的目录,则可以从任何单个listdir中断开。基本上,我正在搜索(.TXT)文件,但我想避免包含大型DPX图像序列(通常为10,000个文件)的目录。由于DPX本身位于没有子目录的目录中,因此我想尽快中断该循环。

简而言之,如果python遇到匹配“.DPX $”的文件,它将停止列出子目录,退出,跳过该子目录,然后继续遍历其他子目录。

是否可以在返回所有列表结果之前中断目录列表循环?

最佳答案

避免使用os.listdir分配名称列表的正确方法是使用操作系统级别的函数,如@Charles Duffy所说。

从其他帖子中得到启发:List files in a folder as a stream to begin process immediately

我添加了如何解决特定OP问题的方法,并使用了函数的可重入版本。

from ctypes import CDLL, c_char_p, c_int, c_long, c_ushort, c_byte, c_char, Structure, POINTER, byref, cast, sizeof, get_errno
from ctypes.util import find_library

class c_dir(Structure):
    """Opaque type for directory entries, corresponds to struct DIR"""
    pass

class c_dirent(Structure):
    """Directory entry"""
    # FIXME not sure these are the exactly correct types!
    _fields_ = (
        ('d_ino', c_long), # inode number
        ('d_off', c_long), # offset to the next dirent
        ('d_reclen', c_ushort), # length of this record
        ('d_type', c_byte), # type of file; not supported by all file system types
        ('d_name', c_char * 4096) # filename
        )
c_dirent_p = POINTER(c_dirent)
c_dirent_pp = POINTER(c_dirent_p)
c_dir_p = POINTER(c_dir)

c_lib = CDLL(find_library("c"))
opendir = c_lib.opendir
opendir.argtypes = [c_char_p]
opendir.restype = c_dir_p

readdir_r = c_lib.readdir_r
readdir_r.argtypes = [c_dir_p, c_dirent_p, c_dirent_pp]
readdir_r.restype = c_int

closedir = c_lib.closedir
closedir.argtypes = [c_dir_p]
closedir.restype = c_int

import errno

def listdirx(path):
    """
    A generator to return the names of files in the directory passed in
    """
    dir_p = opendir(path)

    if not dir_p:
        raise IOError()

    entry_p = cast(c_lib.malloc(sizeof(c_dirent)), c_dirent_p)

    try:
        while True:
            res = readdir_r(dir_p, entry_p, byref(entry_p))
            if res:
                raise IOError()
            if not entry_p:
                break
            name = entry_p.contents.d_name
            if name not in (".", ".."):
                yield name
    finally:
        if dir_p:
            closedir(dir_p)
        if entry_p:
            c_lib.free(entry_p)

if __name__ == '__main__':
    import sys
    path = sys.argv[1]
    max_per_dir = int(sys.argv[2])
    for idx, entry in enumerate(listdirx(path)):
        if idx >= max_per_dir:
            break
        print entry

关于Python Walk,但线程轻而易举,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10454540/

10-12 18:12