need dict to maintain order
Jason Orendorff
jason at jorendorff.com
Sat Jan 19 14:35:28 EST 2002
> Here's what I was able to come up with (constantly referring to the
> man/tut :)). Maybe someone finds it... hmmm... useful and/or enjoys
> commenting newbies' code :)
Not bad at all! Some random comments...
> fullname = self.dirname + '\\' + self.links[self.cur_link][0]
Try os.path.join() for this. It's more portable.
> try:
> os.mkdir(self.dirname)
> except OSError:
> pass
It's better to do
if not os.path.isdir(self.dirname):
os.mkdir(self.dirname)
and not squelch the error, if one occurs.
* * *
For such simple tasks, it's interesting to see what could be done
with a more procedural, non-OO approach. Here's another way to
write your program -- in half as much code. I find it easier to
follow the flow of this version; YMMV.
import os
class Style:
""" Lightweight object encapsulating style parameters. """
def __init__(self, start, end, sep):
self.start = start
self.end = end
self.separator = sep
horz_style = Style('<div class="navbar-horiz">[ ', ' ]</div>', '\n | ')
vert_style = Style('<div class="navbar-vert">', '</div>', '<br><br>\n')
def build_navbars(dirname, links, style):
if not os.path.isdir(dirname):
os.mkdir(dirname)
for filename, title in links:
# Open the file and write the header.
fullpath = os.path.join(dirname, filename)
f = open(fullpath, 'w')
f.write(style.start)
# Build the list of links.
nav_list = []
for link, caption in links:
if link == filename:
nav = '<span class="disabled-link">%s</span>' % caption
else:
nav = '<a href="%s">%s</a>' % (link, caption)
nav_list.append(nav)
# Write all links to the file, with separators.
f.write(style.separator.join(nav_list))
# Write the footer and close the file.
f.write(style.end)
f.close()
if __name__ == '__main__':
links = [
('index.html', 'Home'),
('prog.html', 'Programming'),
('doc.html', 'Docs')
]
build_navbars('navbar_horz', links, horz_style)
build_navbars('navbar_vert', links, vert_style)
## Jason Orendorff http://www.jorendorff.com/
More information about the Python-list
mailing list