iterating over lines in a file

David Bolen db3l at fitlinxx.com
Mon Jul 24 13:51:30 EDT 2000


nobody <no at bo.dy> writes:

> what i was actually trying to do was a prepend-this-string-to-that-file
> routine, and i think i got it. the straight translation from perl got
> really, really long due to all the try-except pairs; i like exceptions
> better than perl's "do {} or die" idiom as they're clearer and seem more
> flexible, but they're sure more verbose, too.

You may find that by applying the exception handling more
strategically, that you can both streamline your code and make it more
readable.

If you're used to checking result codes from a function, the
inclination is probably to place every function call in its own
try/except clause, which can lead to pretty verbose code.  But if you
look at the problem from the perspective of recovery, you'll probably
find that your exception handling makes more sense at a higher level
than the lowest function calls.

For example, in your function to prepend-this-string-to-that-file, you
probably have several operations that can fail (the open, the I/O, and
so on).  But it's the integrity of the overall operation that you are
probably concerned with, so I'd expect that a single try/except clause
around the operation in general would be sufficient for exception
handling.  Without seeing the code, I'd bet that the failure course is
pretty similar regardless of how or where within the process of
prepending the line things fail.  (Of course, I could be wrong too :-))

--
-- David
--
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list