[Tutor] How to open the closed file again?
davea at ieee.org
Tue Jan 5 15:41:12 CET 2010
Andre Engels wrote:
> On Tue, Jan 5, 2010 at 1:46 PM, 朱淳 <zhuchunml at gmail.com> wrote:
>> I've token a dictionary to save filenames, and write it into "constant.py".
>> And I think it's a good method to create a class as Andre wrote. Thank you
>> By the way, if I close a open file object, will the closed file object still
>> occupy the memory ? As I saw in a list, this kind of unusable file object
>> wasn't cleaned by GC. What will happen if there's no list?
> In general, when an object is not referred any more in Python code, it
> will be garbage collected (and thus the memory it occupies will become
> free); however, this is not robust nor fully consistent over
> implementation, and it is therefore unadvisable to write code that
> relies too heavily on this.
If I believed that, clearly I would not use Python for anything real.
I think you're confusing the issue of things like file objects
automatically closing their resources when they go out of scope. That's
not guaranteed to happen in any reasonable time. And you should use a
context manager such as *with* or do explicit close in a try/finally
However, although garbage collection may be lazier in one implementation
than another, if you attempt to program explicit del for all allocated
objects, you might as well use C. Further, there are more invisible
objects being created and destroyed than the ones you have control
over. You have to trust the mechanism, whether it's ref counting or
gc. Incidentally, del doesn't free the object. It just removes one
reference to it. It still may be gc'ed now, or later, and of course not
at all if there are other references to it.
In other words, when an object holds a scarce resource, do some explicit
boxing on it to assure the resource is released. If it's memory, ignore it.
Back to 朱淳 :
Those objects still existed because they were referenced in the list.
You could del them from the list, or replace them with different
objects. Same is true for "scalar variables" (to borrow a term from
other languages). If you say X = obj then the object will exist at
least as long as X is unchanged. If you say X = otherobj or X = None
(which is another singleton object) then the reference to the original
object goes away. And sooner or later, it'll get gc'ed. If you say
del X, then not only the reference goes away, but X is no longer in the
More information about the Tutor