Meine Variante kann man noch vereinfachen, denn ich if Abfrage kann man sich sparen.
externd ist wohl auch schneller als ein +=
Statt os.listdir nutzte ich auch eigentlich dircache.listdir, was nochmal ein tick schneller ist
Ich nutzte dir_walk2():
Code: Alles auswählen
import timeit, os, dircache
def dir_walk1(path):
result = []
for name in os.listdir(path):
if name.startswith("."):
continue
abs_path = os.path.join(path, name)
if not os.path.isdir(abs_path):
continue
result.append(abs_path)
result.extend(dir_walk1(abs_path))
return result
#_____________________________________________________________________________
def dir_walk2(path):
result = []
for name in dircache.listdir(path):
if name.startswith("."):
continue
abs_path = os.path.join(path, name)
if not os.path.isdir(abs_path):
continue
result.append(abs_path)
result.extend(dir_walk1(abs_path))
return result
#_____________________________________________________________________________
def dir_walk3(path):
found = []
for root, dirs, files in os.walk(path):
for d in dirs:
if d.startswith('.'):
dirs.remove(d)
else:
found.append(os.path.join(root, d))
return found
#_____________________________________________________________________________
loop = 100
tests = (
("dir_walk1('.')", "from __main__ import os, dir_walk1"),
("dir_walk2('.')", "from __main__ import os, dircache, dir_walk2"),
("dir_walk3('.')", "from __main__ import os, dir_walk3"),
)
for no, test in enumerate(tests):
print "%s - %s" % (no+1, test[0])
test = timeit.Timer(test[0], test[1])
print "%.2f" % test.timeit(number=loop)
print
Ergebnis:
Code: Alles auswählen
1 - dir_walk1('.')
4.10
2 - dir_walk2('.')
3.75
3 - dir_walk3('.')
5.07
Finde jetzt nicht, das dir_walk2() wesentlich undurchsichtiger wäre als dir_walk3()...
Später kommt evtl. noch eine "skip-Liste" hinzu...