473,386 Members | 1,598 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Changing a value for each folder while traversing a file system

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()

Jul 26 '06 #1
6 1698
PipedreamerGrey wrote:
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()
Add a color attribute to the DirectoryWalker class, change it when you
change directories, return it with the fullname. Change your for loop
like so:

for color, file in DirectoryWalker("."):
# ...

I think that should work.

HTH,
~Simon

Jul 26 '06 #2
No, that doesn't work. Though, leaving the random snippet about the
"for file in DirectoryWalker("."):" line, it does leave all files the
same value, rather than switching the value for every single file. The
problem is, the value is shared accross every folder.

Jul 27 '06 #3
PipedreamerGrey wrote:
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.
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")
You have to remember which directory you are in:

#untested
last_directory = None
for file in DirectoryWalker("."):
directory = os.dirname(file)
if directory != last_directory:
color = random.choice(["red", "green", "blue"])
last_directory = directory

# do whatever you want with file and color
print color, file

Peter

Jul 27 '06 #4
That seems logical, but the syntax doesn't work. I keep getting the
error:
'module object' has no attribute 'dirname'

Jul 27 '06 #5
PipedreamerGrey wrote:
That seems logical, but the syntax doesn't work. I keep getting the
error:
'module object' has no attribute 'dirname'
os.dirname() was a typo, try os.path.dirname().

Peter
Jul 27 '06 #6
Perfect. That's exactly what I wanted. Thanks.

For those reading this later on, the following script will crawl
through a directory, select all the text files, dump them into seperate
numbered html files in the parent directory (in which the python script
is executed). In this example, the first line of the text file is
placed into a table with a randomly colored background. With a little
work, the text files can be complexly formatted, each folder can be
color coded, etc.

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

count == 1
number == 1

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("."):
last_directory = None
for file in DirectoryWalker("."):
issue = number +".html"
directory = os.path.dirname(file)
if directory != last_directory:
color = random.choice(["#990000", "#009900", "#000099"])
last_directory = directory

# 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...
issue.write("<html><head></head><body>")
for line in fileContent:
if not line.startswith("\n"):
if count == 1:
issue.write('<table bgcolor="'+color+'" width="100%"
border="0" cellspacing="0" cellpadding="0"><tr><td>')
issue.write(line)
issue.write("</td></tr></table>")
count = count + 1
else:
issue.write("<p>")
issue.write(line)
issue.write("</p>")
issue.write("</body></html>")
issue.close()

Jul 28 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Anatoly | last post by:
I'm trying to use VB.NET's 2003 ConfigurationSettings.AppSettings.Set() method of updating values but getting error "Collection is read-only". How can I change values of keys in the App.config...
1
by: Wayne | last post by:
I'm using the following code from the Access Web to open a folder. The folder opens in "List" View. Is there an addition that I can make to the code to force the folder to open in "Details" view?...
5
by: Mark Fox | last post by:
Hello, When you add a new web form in VS.NET it automatically adds the following namespaces at the top: using System; using System.Collections; using System.ComponentModel; using...
2
by: Grzegorz Kaczor | last post by:
Hello, I have an ASP.NET application in my website in virtual folder A. This folder contains the application itself. I also have a data virtual directory B which contains data that can be seen...
9
by: Bill Nguyen | last post by:
I need a VB routine to loop thru a select top folder to find all subfolders and list all subfolders/files under each of these subfolders. Any help is greatly appreciated. Bill
1
by: sunil | last post by:
Hi, I want to change the default installation folder to my own path. I did it by changing the application folder's DefaultLocation property. The installation works fine as long the path that I...
1
by: flavourofbru | last post by:
Hello, I am trying to traverse and tree and want to assign the node id for each node in the tree. It would be great if someone helps me with it. Here is the code which i am using and the...
7
by: franc sutherland | last post by:
Hi everyone, I am using Access 2003. I have a database with a table in it which is linked to an excel spreadsheet. When I install the database on someone else's system, the pathname to the...
2
by: fran7 | last post by:
Hi, I wonder if anyone could tell me if there is a default upload folder for image uploads in this code or if the code references another file. It works fine but I am trying to change the upload...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.