How to visit directory tree recursively

Walking the Directory Tree


import os# www .java 2  s  .  c  om
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)

Searching for Files Based on Extension

      
import os# from w ww.  j  a va2  s  .  co  m
path = "/books/python"
pattern = "*.py;*.doc"

def printFiles(dirList, spaceCount, typeList):
    for file in dirList:
        for ext in typeList:
            if file.endswith(ext):
                print "/".rjust(spaceCount+1) + file
                break

def printDirectory(dirEntry, typeList):
    print dirEntry[0] + "/"
    printFiles(dirEntry[2], len(dirEntry[0]),
typeList)

extList = []
for ext in pattern.split(";"):
    extList.append(ext.lstrip("*"))


for directory in os.walk(path):
    printDirectory(directory, extList)
  




















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module