[英]Python 3: Copying the most recent file in a large directory
因此,当标题出现时,我正在尝试确定并复制大目录中的最新文件。 我找到的大多数解决方案要么首先列出目录,要么使用glob.glob
,然后使用max(file, key=os.path.getmtime)
来确定最新文件。
我的问题是我试图搜索的目录有超过10,000个文件,列出所有这些文件需要永远。
有没有办法我可以“取消”列表,可以这么说,一旦我确定了第一个(最新的)文件是什么? 或者也许是另一种我不知道的方法?
您可以使用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.
这可能比glob
快一些,因为walk
不进行模式匹配。 与listdir
相比,它不会使用子目录填充列表,如果这是一个问题。
瓶颈可能是缓慢的系统调用stat
,所以一些启发式可以帮助你跳过不可能的路径,而不是stat
荷兰国际集团他们,如果你已经知道了一些关于可能的结果。
请注意,这只是一个概念证明。 与一般的系统编程一样,您必须仔细处理并发症和异常。 这是一项非常重要的任务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.