我正在尝试用 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 ofos.listdir()
that also exposes the extra file information the operating system returns when you iterate a directory.scandir
also provides a much faster version ofos.walk()
, because it can use the extra file information exposed by thescandir()
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/