In Python, how to find all the files under a directory, including the files in subdirectories?
file, list, python
Solution
There is no built-in function, but using `os.walk` it's trivial to construct it:
import os
def recursive_file_gen(mydir):
for root, dirs, files in os.walk(mydir):
for file in files:
yield os.path.join(root, file)
ETA: the `os.walk` function walks directory tree recursively; the `recursive_file_gen` function is a generator (uses `yield` keyword to produce next file). To get the resulting list do:
list(recursive_file_gen(mydir))
Problem
Is there any built in functions to find all the files under a particular directory including files under subdirectories ? I have tried this code, but not working...may be the logic itself is wrong... ``` def fun(mydir): lis=glob.glob(mydir) length=len(lis) l,i=0,0 if len(lis): while(l+i<length): if os.path.isfile(lis[i]): final.append(lis[i]) lis.pop(i) l=l+1 i=i+1 else: i=i+1 print final fun(lis) else: print final ```