加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 遍历目录

发布时间:2020-12-20 13:29:55 所属栏目:Python 来源:网络整理
导读:我正在寻找一种方法来遍历包含100,000个文件的目录.使用os.listdir的速度很慢,因为此函数首先从整个指定路径中获取路径列表. 什么是最快的选择? 注意:投票的人从未面对过这种情况. 解决方法 另一个问题在评论中被称为副本: List files in a folder as a s
我正在寻找一种方法来遍历包含100,000个文件的目录.使用os.listdir的速度很慢,因为此函数首先从整个指定路径中获取路径列表.

什么是最快的选择?

注意:投票的人从未面对过这种情况.

解决方法

另一个问题在评论中被称为副本:
List files in a folder as a stream to begin process immediately

……但我发现这个例子半不工作.这是适用于我的固定版本:

from ctypes import CDLL,c_int,c_uint8,c_uint16,c_uint32,c_char,c_char_p,Structure,POINTER
from ctypes.util import find_library

import os

class c_dir(Structure):
    pass

class c_dirent(Structure):
    _fields_ = [ 
        ("d_fileno",c_uint32),("d_reclen",c_uint16),("d_type",c_uint8),("d_namlen",("d_name",c_char * 4096),# proper way of getting platform MAX filename size?
        # ("d_name",c_char * (os.pathconf('.','PC_NAME_MAX')+1) ) 
    ]

c_dirent_p = POINTER(c_dirent)
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

# FIXME Should probably use readdir_r here
readdir = c_lib.readdir
readdir.argtypes = [c_dir_p]
readdir.restype = c_dirent_p

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

def listdir(path):
    """
    A generator to return the names of files in the directory passed in
    """
    dir_p = opendir(".")
    try:
        while True:
            p = readdir(dir_p)
            if not p:
                break
            name = p.contents.d_name
            if name not in (".",".."):
                yield name
    finally:
        closedir(dir_p)


if __name__ == "__main__":
    for name in listdir("."):
        print name

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读