在 python 中递归搜索文件的最快方法是什么?
What's the fastest way to recursively search for files in python?
我需要通过递归搜索生成一个文件列表,其路径包含特定字符串。我目前是这样做的:
for i in iglob(starting_directory+'/**/*', recursive=True):
if filemask in i.split('\')[-1]: # ignore directories that contain the filemask
filelist.append(i)
这行得通,但在抓取大型目录树时,速度非常慢(约 10 分钟)。我们在 Windows,因此无法对 unix find 命令进行外部调用。我的理解是 glob 比 os.walk 快。
有没有更快的方法?
也许不是您想要的答案,但我认为这些时间安排很有用。 运行 在一个目录上有 15,424 个目录,总共 102,799 个文件(其中 3059 个是 .py 文件)。
Python 3.6:
import os
import glob
def walk():
pys = []
for p, d, f in os.walk('.'):
for file in f:
if file.endswith('.py'):
pys.append(file)
return pys
def iglob():
pys = []
for file in glob.iglob('**/*', recursive=True):
if file.endswith('.py'):
pys.append(file)
return pys
def iglob2():
pys = []
for file in glob.iglob('**/*.py', recursive=True):
pys.append(file)
return pys
# I also tried pathlib.Path.glob but it was slow and error prone, sadly
%timeit walk()
3.95 s ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit iglob()
5.01 s ± 19.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit iglob2()
4.36 s ± 34 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
在 cygwin (4.6.0-1) 上使用 GNU find (4.6.0)
编辑:下面是 WINDOWS,LINUX 我发现 find
快了大约 25%
$ time find . -name '*.py' > /dev/null
real 0m8.827s
user 0m1.482s
sys 0m7.284s
似乎 os.walk
和 windows 一样好。
我需要通过递归搜索生成一个文件列表,其路径包含特定字符串。我目前是这样做的:
for i in iglob(starting_directory+'/**/*', recursive=True):
if filemask in i.split('\')[-1]: # ignore directories that contain the filemask
filelist.append(i)
这行得通,但在抓取大型目录树时,速度非常慢(约 10 分钟)。我们在 Windows,因此无法对 unix find 命令进行外部调用。我的理解是 glob 比 os.walk 快。
有没有更快的方法?
也许不是您想要的答案,但我认为这些时间安排很有用。 运行 在一个目录上有 15,424 个目录,总共 102,799 个文件(其中 3059 个是 .py 文件)。
Python 3.6:
import os
import glob
def walk():
pys = []
for p, d, f in os.walk('.'):
for file in f:
if file.endswith('.py'):
pys.append(file)
return pys
def iglob():
pys = []
for file in glob.iglob('**/*', recursive=True):
if file.endswith('.py'):
pys.append(file)
return pys
def iglob2():
pys = []
for file in glob.iglob('**/*.py', recursive=True):
pys.append(file)
return pys
# I also tried pathlib.Path.glob but it was slow and error prone, sadly
%timeit walk()
3.95 s ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit iglob()
5.01 s ± 19.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit iglob2()
4.36 s ± 34 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
在 cygwin (4.6.0-1) 上使用 GNU find (4.6.0)
编辑:下面是 WINDOWS,LINUX 我发现 find
快了大约 25%
$ time find . -name '*.py' > /dev/null
real 0m8.827s
user 0m1.482s
sys 0m7.284s
似乎 os.walk
和 windows 一样好。