Allowing ref counting to close file items bad style?

Dan bounces at foo.org
Tue Aug 29 22:40:05 EDT 2006


Is this discouraged?:

     for line in open(filename):
         <do something with line>

That is, should I do this instead?:

     fileptr = open(filename)
     for line in fileptr:
         <do something with line>
     fileptr.close()

Can I count on the ref count going to zero to close the file?

How about a write case?  For example:

     class Foo(list):
         def __init__(self):
             self.extend([1, 2, 3, 4])
         def write(self, fileptr):
             for item in self:
                 fileptr.write("%s\n" % item)

     foo_obj = Foo()
     foo_obj.write(open("the.file", "w"))

Is my data safer if I explicitly close, like this?:
     fileptr = open("the.file", "w")
     foo_obj.write(fileptr)
     fileptr.close()

I understand that the upcoming 'with' statement will obviate this 
question, but how about without 'with'?

/Dan

-- 
dedded att verizon dott net



More information about the Python-list mailing list