File Handling & TRY/EXCEPT

Robert Rawlins - Think Blue robert.rawlins at thinkbluemedia.co.uk
Fri Aug 3 04:23:53 EDT 2007


Hello Guys,

 

I'm looking for some advice on how best to handle file read/write errors
with try/except as i'm a little vague on this, I have a small memory leak in
my app and I'm starting to think its generated by my log file write. For an
example of the function look below.

 

       def addAppLog(self, event):

              try:

                     logfile = open('/pblue/new/Logs/Application.csv','a')

 

                     now = datetime.datetime.now()

 

                     logstring = '%s,%s \n' % (event, str(now))

 

                     logfile.write(logstring)

              except:

                     self.addAppLog(event)

              else:

                     logfile.close()

 

Now I'm looking for some help to sort this out as I'm sure it's pretty
untidy, I want to make it as air tight as possible. The basic concept was
that if it tries writing to the log file and it fails, then it needs to
reattempt it, right?

 

What's the best way to handle this to ensure that there are not any memory
leaks caused when the file is open() but not followed by a close(). I'm
running 2.4 and I know some of these newer versions don't need you to
explicitly close() the file objects, but I would certainly feel a lot
better.

 

Any advice?

 

Thanks guys,

 

Rob

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20070803/e932d30f/attachment.html>


More information about the Python-list mailing list