[Tutor] os.walk()

Alan Gauld alan.gauld at btinternet.com
Thu Aug 3 11:49:52 CEST 2006


"Christopher Spears" <cspears2002 at yahoo.com> wrote> for 
root,dirs,files in os.walk(base):
> for name in files:
> path = os.path.join(root, name)
> print path
>
> Sample output:
>
> ./gui_screenshot.jpeg
> ./find_items.pyc
> ./find_items.py
> ./os
> ./LearningToProgram/loggablebankaccount.py

> I'm glad that the function works smoothly.  I'm just
> wondering how os.walk works.  Shouldn't I have to
> write a statement like this:
>
> path = os.path.join(root, dirs, name)
>

No, the dirs value holds a list of folders, the files
value holds a list of files. Thus if you wanted to print
out all the sub folders in the root you would
print root+dirs
But you want files not folders so you correctly use
print root+files

root holds the full path to the current point in the tree.
(And os.walk is a good example of a program using a
tree data structure! ;-)

Alan G. 





More information about the Tutor mailing list