[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

This call isn’t as commonly used (and can be emulated with a simple for loop or other
iteration tool), but it is convenient in scripts that save output in a list to be written later.


The file close method used earlier finalizes file contents and frees up system
resources. For instance, closing forces buffered output data to be flushed out to disk.
Normally, files are automatically closed when the file object is garbage collected by the
interpreter (that is, when it is no longer referenced). This includes all remaining open
files when the Python session or program exits. Because of that, close calls are often
optional. In fact, it’s common to see file-processing code in Python in this idiom:


open('somefile.txt', 'w').write("G'day Bruce\n") # write to temporary object
open('somefile.txt', 'r').read() # read from temporary object

Since both these expressions make a temporary file object, use it immediately, and do
not save a reference to it, the file object is reclaimed right after data is transferred, and
is automatically closed in the process. There is usually no need for such code to call the
close method explicitly.


In some contexts, though, you may wish to explicitly close anyhow:



  • For one, because the Jython implementation relies on Java’s garbage collector, you
    can’t always be as sure about when files will be reclaimed as you can in standard
    Python. If you run your Python code with Jython, you may need to close manually
    if many files are created in a short amount of time (e.g. in a loop), in order to avoid
    running out of file resources on operating systems where this matters.

  • For another, some IDEs, such as Python’s standard IDLE GUI, may hold on to
    your file objects longer than you expect (in stack tracebacks of prior errors, for
    instance), and thus prevent them from being garbage collected as soon as you might
    expect. If you write to an output file in IDLE, be sure to explicitly close (or flush)
    your file if you need to reliably read it back during the same IDLE session. Other-
    wise, output buffers might not be flushed to disk and your file may be incomplete
    when read.

  • And while it seems very unlikely today, it’s not impossible that this auto-close on
    reclaim file feature could change in future. This is technically a feature of the file
    object’s implementation, which may or may not be considered part of the language
    definition over time.


For these reasons, manual close calls are not a bad idea in nontrivial programs, even if
they are technically not required. Closing is a generally harmless but robust habit to
form.


Ensuring file closure: Exception handlers and context managers


Manual file close method calls are easy in straight-line code, but how do you ensure
file closure when exceptions might kick your program beyond the point where the close
call is coded? First of all, make sure you must—files close themselves when they are
collected, and this will happen eventually, even when exceptions occur.


Closing.


File Tools | 139
Free download pdf