[Tutor] Would an OOP approach be simpler?

Kent Johnson kent37 at tds.net
Wed Nov 10 11:50:03 CET 2004


Jacob S. wrote:
> Hi all!
> 
> 
>>def checkIfDoesExist(weekstart):
>>   if os.path.exists('./archives/wb%s' % weekstart):
>>       done=file('./archives/wb%s/got.lst' %weekstart, 'rb')
>>       donelist=done.readlines()
>>       done.close()
>>       list=donelist[0].split('/')
>>       return (list, 1)
>>   else:
>>       return (None, 0)
> 
> 
> Okay, three things.
> 
> 1) Does this section of code do the same thing?
> 
> def checkIfDoesExist(weekstart):
>     a = './archives/wb%s' % weekstart
>     if os.path.exists(a):
>         li = file(a,'rb').readlines()[0].split('/')
>         return (li,1)
>     else:
>         return (None,0)
> 

It opens a different file - wbweekstart vs wbweekstart/got.lst
As you noted, it doesn't explicitly close the file. This is common - 
Python will close the file when it exits. I recommend you explicitly 
close files that you write, don't worry about it for files you open for 
read.

> 2) Do any of you advise against/for my modified code block?

It's short and sweet. BTW you could use readline().split('/') instead of 
readlines()[0].split() - there is no need to read the whole file when 
you just need the first line.

Kent

> 3) Does li automatically close? The file seems accessible even though I
> haven't explicitly closed it.
> 
> Thanks for answering these when you get around to it.
> Jacob Schmidt
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list