[Tutor] os.walk()

Christopher Spears cspears2002 at yahoo.com
Thu Aug 3 00:42:10 CEST 2006


I'm creating a function that traverses a directory
tree and prints out paths to files:

#!/usr/bin/python

import os, os.path, glob

def traverse(base = '.'):
	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
./LearningToProgram/BankAccounts.pyc
./LearningToProgram/KeysApp.py
./LearningToProgram/Message.py
./LearningToProgram/Message.pyc
./LearningToProgram/a.txt
./LearningToProgram/b.txt

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)




More information about the Tutor mailing list