Skip to content
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 24 additions & 5 deletions Doc/tutorial/inputoutput.rst
Original file line number Diff line number Diff line change
Expand Up @@ -329,11 +329,30 @@ equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::

If you're not using the :keyword:`with` keyword, then you should call
``f.close()`` to close the file and immediately free up any system
resources used by it. If you don't explicitly close a file, Python's
garbage collector will eventually destroy the object and close the
open file for you, but the file may stay open for a while. Another
risk is that different Python implementations will do this clean-up at
different times.
resources used by it. :meth:`__del__` of the returned :term:`file object` also calls ``f.close()``.
Comment thread
methane marked this conversation as resolved.
Outdated

..
Source for the claim that the ``del(f)`` calls .close():
Take a look at the source code of open() in _pyio.py and check the
returned type. It will always be one of these 5 classes:
FileIO
TextIOWrapper
BufferedRandom
BufferedWriter
BufferedReader
FileIO defines the __del__ method that calls .close().
The other 4 classes inherit indirectly (without overwriting __del__) from
IOBase which defines the __del__ method that calls .close().

.. warning::
Calling ``f.write()`` without using the :keyword:`!with` keyword or calling
``f.close()``, ``f.flush()`` or ``del f`` **might** result in the arguments
Comment thread
Volker-Weissmann marked this conversation as resolved.
Outdated
of ``f.write()`` not being completely written to the disk, even if the
program exists successfully. This is because Python does not guarantee that
:meth:`__del__` is called when the interpreter exists.
Comment thread
methane marked this conversation as resolved.
Outdated
Comment thread
methane marked this conversation as resolved.
Outdated

..
See also https://bugs.python.org/issue17852

After a file object is closed, either by a :keyword:`with` statement
or by calling ``f.close()``, attempts to use the file object will
Expand Down