我在一个大硬盘上使用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)
发布于 2014-12-19 19:43:29
我研究了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)
https://stackoverflow.com/questions/8931099
复制相似问题