"sins" (aka, acknowledged language problems)
Will Rose
cwr at cts.com
Sat Dec 18 02:06:09 EST 1999
Alex Martelli <Alex.Martelli at think3.com> wrote:
[...]
: I (think I) need a simple "template" sort of
: operation whereby an input stream (mostly a
: file) is copied to an output (ditto), with some
: kind of "substitution" happening on the fly, and
: a reasonable amount of generality. There is
: sure to be something around, but, hey, I'm a
: newbie, I need to learn, so yesterday evening
: I decide to design my own -- looks like trying to
: implement it may make for a nice weekend kind
: of project. Starting from a newbie's vague
: acquaintance with Python facilities, I reason...:
: Let's see -- basically I want line by line copying
: of an input "template" stream, to an output one,
: while some variables get substituted. But why
: just variables -- let's make it expressions -- the
: "eval" builtin should make those just as easy, I
: think. But how do I demarcate the expressions,
: any given syntax I might choose would surely
: be awkward for some uses. Hmm, regular
: expressions should help -- the caller will pass
: me a re, and the first parenthesized group in
: it will be the expression to eval, with which the
: re itself will be substituted -- neat. Of course,
: I'll also need a dictionary for the eval itself.
I messed with this problem the other day, and ended up
with (roughly):
for filename in filenames:
try:
# scan the input file
fpin = open(filename, "r")
lines = fpin.readlines()
newlines = []
for line in lines:
newline = cleanline(line)
newlines.append(newline)
fpin.close()
os.remove(filename)
# write out the results
fpout = open(filename, "w")
fpout.writelines(newlines)
fpout.close()
except IOError, badthing:
print sys.exc_value
Cleaner than the setup you used, but not the way I'd have
chosen to write the program - I'd have preferred to read
and write single lines at a time. However, the files I
was working on were all < 10K, so I accepted the additional
memory usage.
My initial shot used a line count variable in addition to
the for loop, and was really clumsy. It would be nice if
there were some built-in index to a for loop, but I can't
see how it could be reliably implemented.
Will
cwr at crash.cts.com
More information about the Python-list
mailing list