A little assistance with os.walk please.

Larry Bates larry.bates at websafe.com
Mon Aug 14 11:23:13 EDT 2006


KraftDiner wrote:
> The os.walk function walks the operating systems directory tree.
> 
> This seems to work, but I don't quite understand the tupple that is
> returned...
> Can someone explain please?
> 
> for root, dirs, files in os.walk('/directory/'):
> 	print root
> #	print dirs
> #	print files
> 

Actually returns two tuples: dirs and files

root - is the directory branch you are currently walking
dirs - are the directory branches that are subdirectories of this
       directory branch
files - are the files that live in this directory branch


To process all the files here you do something like:

for afile in files:  # resist the urge to call it 'file'
     fullpath=os.path.join(root, afile)
     #
     # Do something  with fullpath
     #

Hard to figure out item - If you wish to NOT process some of the
dirs, you can delete them from the dirs list here and they won't
get walked.  You MUST delete them in place with del dirs[n] or
dirs.pop or some other function that deletes in-place.

You might want to type: help(os.walk) to get some more info.

-Larry Bates



More information about the Python-list mailing list