473,545 Members | 2,714 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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__(sel f, 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(se lf.directory, file)
if os.path.isdir(f ullname) and not
os.path.islink( fullname):
self.stack.appe nd(fullname)
else:
return fullname

for file in DirectoryWalker ("."):
# divide files names into path and extention
path, ext = os.path.splitex t(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(col or)
for line in fileContent:
if not line.startswith ("\n"):
index.write(lin e)
index.write("\n ")

index.close()

Jul 26 '06 #1
6 1711
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__(sel f, 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(se lf.directory, file)
if os.path.isdir(f ullname) and not
os.path.islink( fullname):
self.stack.appe nd(fullname)
else:
return fullname

for file in DirectoryWalker ("."):
# divide files names into path and extention
path, ext = os.path.splitex t(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(col or)
for line in fileContent:
if not line.startswith ("\n"):
index.write(lin e)
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.splitex t(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(col or)
for line in fileContent:
if not line.startswith ("\n"):
index.write(lin e)
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__(sel f, 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(se lf.directory, file)
if os.path.isdir(f ullname) and not
os.path.islink( fullname):
self.stack.appe nd(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.splitex t(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("<h tml><head></head><body>")
for line in fileContent:
if not line.startswith ("\n"):
if count == 1:
issue.write('<t able bgcolor="'+colo r+'" width="100%"
border="0" cellspacing="0" cellpadding="0" ><tr><td>')
issue.write(lin e)
issue.write("</td></tr></table>")
count = count + 1
else:
issue.write("<p >")
issue.write(lin e)
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
9550
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 file programatically? Here is my code: Imports System.Configuration Imports System.Collections.Specialized
1
2601
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? 'This code was originally written by Ken Getz. 'It is not to be altered or distributed, 'except as part of an application. 'You are free to use...
5
1603
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 System.Data; using System.Drawing;
2
1411
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 by authenticated users. I've implemented forms authentication (with application in folder A) in a standard way. I've also set up a redirection in...
9
18978
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
8902
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 give is complete path. If I give relative path, there is an error. The path is relative to the location of my solution folder. Just to be more clear,...
1
2192
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 problem is the nodes in the tree are repeating everytime and i want to visit each node only once and assign the node id to it. protected void...
7
8417
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 excel file is different. Howwever, as it is in runtime on their system, I can't update the link using the Linked Table Manager. Is there a way of...
2
2166
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 folder for images and cannot find where its done. This bit confuses me as the application gcp, I simply dont know where it is. The only include in this...
0
7434
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7692
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7946
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7457
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7791
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6026
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3491
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1921
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1045
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.