Python 3:复制大目录中的最新文件

rea*_*exe 5 python python-3.x

因此,正如标题所示,我正在尝试确定并复制大目录中的最新文件。我发现的大多数解决方案要么首先列出目录,要么使用glob.glob, 然后使用max(file, key=os.path.getmtime)来确定最新的文件。

我的问题是我试图搜索的目录有超过 10,000 个文件,列出所有这些文件需要很长时间。

有没有办法可以“取消”列表,可以这么说,一旦我确定了第一个(最近的)文件是什么?或者我不知道的另一种方法?

Con*_* Ma 2

您可以使用os.walk迭代目录并应用于max生成器。根据您的使用情况,有很多细微差别。例如,您想要浅层地还是递归地进入子目录?作为概念证明,您可以尝试类似的方法,但也可以对其进行修改以满足您的需要。

import os
import os.path


def mtime_gen(root, *args, **kwargs):
    for dirpath, dirnames, filenames in os.walk(root, *args, **kwargs):
        # NOTE:
        # Here, if you want to skip the depth-walk into sub-directories,
        # you can ignore the `dirnames`
        for basename in filenames:
            path = os.path.join(dirpath, basename)
            # Further heuristics, if any, may help you skipping impossible
            # candidates of the most recent file with the `continue` statement
            # so that expensive `stat` calls can be omitted.
            yield os.stat(path).st_mtime, path

recent_timestamp, recent_path = max(mtime_gen("/path/to/root"))
do_something_with(recent_path)    # For example, copying it.
Run Code Online (Sandbox Code Playgroud)

这可能比不进行模式匹配要快glob一些walk。相比之下,listdir如果这是一个问题的话,它不会用子目录填充列表。

瓶颈可能是缓慢的系统调用stat,因此stat如果您已经了解可能的结果,一些启发式方法可能会帮助您跳过不可能的路径而不是它们。

请注意,这只是一个概念证明。与一般的系统编程一样,您必须仔细处理复杂情况和异常。这是一项非常重要的任务。