how to get files in a directory

Jeremy Jones zanesdad at bellsouth.net
Wed Sep 29 17:11:48 CEST 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
>
>
Would you mind posting the code that works?  First of all, os doesn't 
have a join, so doing an "from os import walk, join" won't work.  
Second, you don't have an "os" namespace in your script.  Third, if your 
import would've worked, you would have wound up with walk and join in 
your toplevel namespace.  Next, you've got "fille = root + i + j" (two 
letters l in fille) then you try to print "file" (with one l).  This 
code works for me:

import os

for root,dir,files in os.walk("r:\svn\qa"):
    for i in dir:
        for j in files:
            file = root + i + j
            print file

Jeremy Jones



More information about the Python-list mailing list