Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how to find all the files under a directory, including the files in subdirectories?

Tags:

python

file

list

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
like image 513
pythBegin Avatar asked Dec 02 '22 05:12

pythBegin


1 Answers

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))
like image 169
SilentGhost Avatar answered Dec 31 '22 11:12

SilentGhost