file opening and closing

H

hokieghal99

jpg = string.find(file(os.path.join(root,fname), 'rb').read(), 'JFIF')

Should this file be closed after reading? If so, how would one close it?
What's the downside to not closing it?
 
A

anton muhin

hokieghal99 said:
jpg = string.find(file(os.path.join(root,fname), 'rb').read(), 'JFIF')

Should this file be closed after reading? If so, how would one close it?
What's the downside to not closing it?

It would, then the file object gets destroyed (it method __del__ is
called). However, as Python uses garbage collection, it can happen much
later after you leave the function.

There is mostly no downsides except for the cases when you try to read
this file---it might not be flashed.

regards,
anton.
 
D

Donn Cave

Quoth anton muhin <[email protected]>:
| hokieghal99 wrote:
|> jpg = string.find(file(os.path.join(root,fname), 'rb').read(), 'JFIF')
|>
|> Should this file be closed after reading? If so, how would one close it?
|> What's the downside to not closing it?
|
| It would, then the file object gets destroyed (it method __del__ is
| called). However, as Python uses garbage collection, it can happen much
| later after you leave the function.
|
| There is mostly no downsides except for the cases when you try to read
| this file---it might not be flashed.

(Flushed, that is, and of course that wouldn't be a problem here since
the file is only to be read.) Note that the exact behavior here depends
on the implementation: Java Python may as you say defer the close
indefinitely, but C Python will execute it immediately on function return,
because its garbage collection is based on reference count.

The above usage is fine in C Python. In Java Python, it's probably OK
but potential problems would include file descriptor resource starvation
if opening many files this way, and low disk space if reading large files
this way and then deleting them, because the open file descriptor will
preserve the actual file even though its directory entry is gone.

Donn Cave, (e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top