File Handling & TRY/EXCEPT

Alex Popescu nospam.themindstorm at gmail.com
Fri Aug 3 08:28:52 EDT 2007


"Robert Rawlins - Think Blue" <robert.rawlins at thinkbluemedia.co.uk>
wrote in news:33119.3366124809$1186129744 at news.gmane.org: 

> This is a multipart message in MIME format.
> 
> ------=_NextPart_000_00B0_01C7D5B0.02EB8BA0
> 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()
>

Shouldn't you always close the file? So, a finally block with

if logfile:
  logfile.close()

./alex
--
.w( the_mindstorm )p.




More information about the Python-list mailing list