how to get files in a directory

rzed jello at comics.com
Wed Sep 29 18:32:46 CEST 2004


Jeremy Jones <zanesdad at bellsouth.net> wrote in
news:mailman.4081.1096470726.5135.python-list at python.org: 

> 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
> 
Taking Jeremy's code and attempting to print the contents of a 
directory, I see that it fails on my Win2K system when given a path 
like "c:\\dir1\\dir2\\dir3" (regardless of how I specify the path). 

When I print the contents of root, dir and files before entering 
the lower-level loops, I see that *dir* contains an empty list when 
root contains "c:\\dir1\\dir2\\dir3". That is, the contents of the 
lowest-level directory won't be printed out because dir has no list 
elements, although *files* does. So it looks like you'd have to 
check for the empty dir and handle that situation separately.

-- 
rzed




More information about the Python-list mailing list