how to get files in a directory

wes weston wweston at att.net
Wed Sep 29 12:51:21 EDT 2004


Anand K Rayudu wrote:
> 
> Hi all,
> 
> I am trying to find a way to get the files recursively in a given 
> directory,
> 
> The following code is failing, can some one please suggest what could be 
> problem here
> 
> 
> from os import walk,join
> 
> for root,dir,files in os.walk("E:\myDir1\MyDir2"):
>   for i in dir:
>       for j in files:
>           fille = root+i+j
>            print file
> 
> Surprisingly if i give os.walk("E:\myDir1") the above code works, but 
> not if i have 2 levels of directories.
> 
> Thanks & Best Regards,
> Anand
> 
> 

Anand,
    Does this help?
wes

def GetFilesWithExtRecursively(path,ext_list): #ext_list is like [".h",".cpp",...]
     dir_list  = []
     file_list = []
     if not os.path.isdir(path):
         print "\a"
         return [],[]

     filenames = os.listdir( path )

     for fn in filenames:
         if path[-1] == "/":
             xfn = path + fn
         else:
             xfn = path + "/" + fn
         if( os.path.isdir( xfn ) ):
             file_list = file_list + GetFilesWithExtRecursively( xfn ,ext_list)
         elif( os.path.isfile( xfn ) ):
             front,back = os.path.splitext(xfn)
             if back in ext_list:
             	file_list.append( xfn )
     return file_list




More information about the Python-list mailing list