Changing a value for each folder while traversing a file system

PipedreamerGrey pipedreamergrey at gmail.com
Wed Jul 26 10:38:04 EDT 2006


I'm using the script below (originally from http://effbot.org, given to
me here) to open all of the text files in a directory and its
subdirectories and combine them into one Rich text
file (index.rtf).  Now I'm adapting the script to convert all the text
files into individual html files.  What I can't figure out is how to
trigger a change in the background value for each folder change (not
each file), so that text is color-coded by folder.

I have tried to integrate the following snippet into the directory
walker, so that I could later write it to the file as text: color =
random.choice(["#990000", "#CCCCCC", "#000099"])
That method didn't work, does anyone else have a suggestion?


#! /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:
            try:
                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
            else:
                # get a filename, eliminate directories from list
                fullname = os.path.join(self.directory, file)
                if os.path.isdir(fullname) and not
os.path.islink(fullname):
                    self.stack.append(fullname)
                else:
                    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
        file = open(file)
        fileContent = file.readlines()
       # just for example, let's say I want to print the color here as
if in an html tag...
        index.write(color)
        for line in fileContent:
            if not line.startswith("\n"):
                index.write(line)
                index.write("\n")

index.close()




More information about the Python-list mailing list