Walking the Directory Tree


tree = os.walk(path) for directory in tree:     printDirectory(directory)

Python provides a powerful directory tree-walking function in the os module. The walk(path) function will walk the directory tree, and for each directory in the tree create a three-tuple containing (1) the dirpath, (2) a list of dirnames, and (3) a list of filenames.

Once the tuples have been created, they can be processed one at a time as elements of a list. For each tuple, you can access the path to the directory represented directly by using the 0 index into the tuple. Lists of the subdirectories and files contained in the directory can likewise be accessed using the 1 and 2 indexes, respectively.

The example in dir_tree.py shows how to use the os.walk(path) function to walk a directory tree and print out a formatted listing of the tree.

import os path = "/books/python" def printFiles(dirList, spaceCount):     for file in dirList:         print "/".rjust(spaceCount+1) + file def printDirectory(dirEntry):     print dirEntry[0] + "/"     printFiles(dirEntry[2], len(dirEntry[0])) tree = os.walk(path) for directory in tree:     printDirectory(directory)


dir_tree.py

/books/python/              /Python Proposal.doc              /Python_Phrasebook_TOC.doc              /python_schedule.xls              /template.doc              /TOC_Notes.doc /books/python\CH2/                  /ch2.doc /books/python\CH2\code/                       /comp_str.py                       /end_str.py                       /eval_str.py                       /format_str.py                       /join_str.py                       /output.txt                       /replace_str.py                       /search_str.py                       /split_str.py                       /trim_str.py                       /unicode_str.py                       /var_str.py /books/python\CH3/                  /ch3.doc


Output from dir_tree.py code




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net