I am looking to write a function that looks into a given directory and gives me a list of paths of all folders of a particular name.
Let's say I need to search the Desktop and all its subdirectories for folders named "Test". The original code to do it is this:
def finder():
lst = []
for root, dir, files in os.walk(r'C:\Users\username\Desktop'):
for i in dir:
if i == 'Test':
lst.append(os.path.join(root,i))
return lst
I looked online and found that list comprehensions can be much faster in such cases and came up with this function:
def finder2():
lst = [i[0] for i in os.walk(r'C:\Users\username\Desktop') if i[0][-4:]=='Test']
return lst
I timed both functions using timeit for 100 repetitions and found that they take a similar amount of time.
- Why is the list comprehension not faster?
- How can I make it faster?
- Is there any other faster way to do the same thing?
Thanks!