python - 当目录很大时用Python列出目录中的文件

标签 python file sorting directory size

我正在尝试用 Python 处理许多文件。我首先需要获取单个目录中所有文件的列表。目前,我正在使用:

os.listdir(dir)

但是。这是不可行的,因为我正在搜索的目录中有超过 81,000 个文件,总计几乎 5 GB。

逐一浏览每个文件的最佳方法是什么? Windows 没有判定 Python 进程没有响应并杀死它吗?因为这种情况很容易发生。

它在 32 位 Windows XP 计算机上运行,​​因此显然它无法索引超过 4 GB 的 RAM。

任何人都有其他想法来解决这个问题吗?

最佳答案

您可能想尝试使用scandir模块:

scandir is a module which provides a generator version of os.listdir() that also exposes the extra file information the operating system returns when you iterate a directory. scandir also provides a much faster version of os.walk(), because it can use the extra file information exposed by the scandir() function.

有一个 accepted PEP建议将其合并到Python标准库中,因此似乎有一些吸引力。

来自他们文档的简单使用示例:

def subdirs(path):
    """Yield directory names not starting with '.' under given path."""
    for entry in os.scandir(path):
        if not entry.name.startswith('.') and entry.is_dir():
            yield entry.name

关于python - 当目录很大时用Python列出目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25550919/

相关文章:

arrays - 如何根据预定义的元素顺序对数组进行排序?

arrays - Perl:在哈希数组中找到最大值和最小值

Python CLI 框架和带有制表符补全的参数解析

python - datetime.timedelta 返回意外结果?

python - 如何从 Python SAX 解析器返回数据?

python - 在 Python 中对文件内容进行排序

javascript - 输入类型[文件]不显示文件名。 Angularjs

python - 在字符串中搜索符合特定条件的子串

c# - 循环获取 PDF 文件

algorithm - 排序算法从仅具有直角的点创建多边形