I am using os.walk
to build a map of a data-store (this map is used later in the tool I am building)
This is the code I currently use:
def find_children(tickstore):
children = []
dir_list = os.walk(tickstore)
for i in dir_list:
children.append(i[0])
return children
I have done some analysis on it:
dir_list = os.walk(tickstore)
runs instantly, if I do nothing with dir_list
then this function completes instantly.
It is iterating over dir_list
that takes a long time, even if I don't append
anything, just iterating over it is what takes the time.
Tickstore
is a big datastore, with ~10,000 directories.
Currently it takes approx 35minutes to complete this function.
Is there any way to speed it up?
I've looked at alternatives to os.walk
but none of them seemed to provide much of an advantage in terms of speed.
os.walk
is currently quite slow because it first lists the directory and then does astat
on each entry to see if it is a directory or a file.An improvement is proposed in PEP 471 and should be coming soon in Python 3.5. In the meantime you could use the scandir package to get the same benefits in Python 2.7
Yes: use Python 3.5 (which is still currently a RC, but should be out momentarily). In Python 3.5,
os.walk
was rewritten to be more efficient.This work done as part of PEP 471.
Extracted from the PEP:
A method to optimize it in python2.7, use
scandir.walk()
instead ofos.walk()
, the parameters are exactly the same.PS: Just as @recoup mentioned in comment,
scandir
needs to be installed before usage in python2.7.