Expanding Search to Subfolders

PipedreamerGrey pipedreamergrey at gmail.com
Tue Jun 6 10:01:34 EDT 2006

Here's the final working script.  It opens all of the text files in a
directory and its subdirectories and combines them into one Rich text
file (index.rtf):

#! /usr/bin/python
import glob
import fileinput
import os
import string
import sys

index = open("index.rtf", 'w')

class DirectoryWalker:
    # a forward iterator that traverses a directory tree, and
    # returns the filename

    def __init__(self, directory):
        self.stack = [directory]
        self.files = []
        self.index = 0

    def __getitem__(self, index):
        while 1:
                file = self.files[self.index]
                self.index = self.index + 1
            except IndexError:
                # pop next directory from stack
                self.directory = self.stack.pop()
                self.files = os.listdir(self.directory)
                self.index = 0
                # get a filename, eliminate directories from list
                fullname = os.path.join(self.directory, file)
                if os.path.isdir(fullname) and not
                    return fullname

for file in DirectoryWalker("."):
    # divide files names into path and extention
    path, ext = os.path.splitext(file)
    # choose the extention you would like to see in the list
    if ext == ".txt":
        print file

        # print the contents of each file into the index
        file = open(file)
        fileContent = file.readlines()
        for line in fileContent:
            if not line.startswith("\n"):


More information about the Python-list mailing list