python - os.walk 还是 glob 更快?

标签 python traversal glob os.walk directory-walk

我在一个大硬盘上用 python 查找文件。我一直在看 os.walk 和 glob。我通常使用 os.walk,因为我发现它更整洁而且似乎更快(对于通常大小的目录)。

有没有人对这两种方法都有经验,可以说哪个更有效?正如我所说,glob 似乎更慢,但你可以使用通配符等,就像 walk 一样,你必须过滤结果。这是查找核心转储的示例。

core = re.compile(r"core\.\d*")
for root, dirs, files in os.walk("/path/to/dir/")
    for file in files:
        if core.search(file):
            path = os.path.join(root,file)
            print "Deleting: " + path
            os.remove(path)

或者

for file in iglob("/path/to/dir/core.*")
    print "Deleting: " + file
    os.remove(file)

最佳答案

我对 1000 个目录中的一小部分网页缓存进行了研究。任务是计算目录中的文件总数。输出是:

os.listdir: 0.7268s, 1326786 files found
os.walk: 3.6592s, 1326787 files found
glob.glob: 2.0133s, 1326786 files found

如您所见,os.listdir 是三个中最快的。并且 glog.glob 在这个任务中仍然比 os.walk 快。

来源:

import os, time, glob

n, t = 0, time.time()
for i in range(1000):
    n += len(os.listdir("./%d" % i))
t = time.time() - t
print "os.listdir: %.4fs, %d files found" % (t, n)

n, t = 0, time.time()
for root, dirs, files in os.walk("./"):
    for file in files:
        n += 1
t = time.time() - t
print "os.walk: %.4fs, %d files found" % (t, n)

n, t = 0, time.time()
for i in range(1000):
    n += len(glob.glob("./%d/*" % i))
t = time.time() - t
print "glob.glob: %.4fs, %d files found" % (t, n)

关于python - os.walk 还是 glob 更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931099/

相关文章:

python - Scrapy ITEM_PIPELINES 警告

python - TypeError : must be pygame. 表面,不是列表

ruby - 有没有比 Ruby 的 Dir.glob 更快的替代品?

python - 在 python 中使用 glob.glob 排序

java - Spring Reactive Router Path - 带排除的通配符

Python。使用单词列表中的任何单词拆分字符串

python - 字符串到小的固定长度字符串的廉价映射

java - 使用常数空间和 O(n) 运行时间编写二叉搜索树的非递归遍历

javascript - jquery 下一个 sibling

javascript - 嵌套归约函数/递归/函数式编程/树遍历