how to get files in a directory

Michael Kent mrmakent at cox.net
Wed Sep 29 16:41:41 EDT 2004


Anand K Rayudu <ary at esi-group.com> wrote in message news:<mailman.4078.1096469771.5135.python-list at python.org>...
> 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

You don't really give enough information, but I'll make some
reasonable guesses. My guess is that you have a directory tree
"E:\myDir1\MyDir2", and that "MyDir2" contains files but no
subdirectories.

 
> for root,dir,files in os.walk("E:\myDir1\MyDir2"):

Here you are iterating over a directory tree.  For each directory in
the tree, os.walk returns the path to the directory, a list of the
subdirectories in that directory, and a list of non-directory files in
that directory.

>    for i in dir:

Here you are examining each of the subdirectories of the current
directory.  You are ignoring any files in that directory.  So, for the
top-level directory you gave to os.walk, "E:\myDir1\MyDir2", you are
ignoring the actual files in that directory, and examining only its
subdirectories.  My guess is that there are no subdirectories, so you
get no results.

> Surprisingly if i give os.walk("E:\myDir1") the above code works, but 
> not if i have 2 levels of directories.

Unsurprisingly.  If there are any files in "myDir1", your code would
ignore them, and only find files in its subdirectory, "MyDir2".



More information about the Python-list mailing list