[Tutor] file opened by open() are closed automaticaly

Ben Finney ben+python at benfinney.id.au
Sat Jan 14 06:04:21 EST 2017

ZEMMOURA Khalil Zakaria <zemmoura.khalil at gmail.com> writes:

> The file opened using open() is closed automaticaly after iterationg
> over it in the python shell

You can interrogate a file to ask whether it is closed; the ‘closed’
attribute will be True when the file is closed.

> testfile = open('test.txt')
> for line in testfile:
>     print(line)

What happens if you insert this line before the ‘print’ statement::

    for line in testfile:
        assert (not testfile.closed), "file was closed unexpectedly!"

If what you say is true, that ‘assert’ statement will raise an exception
with that custom message.

> the first time the code runs well and gives me the expected result.
> the secod time that i run the loop, nothing is printed on the screen.

If you try to read from a file that is already closed, an error occurs::

    >>> testfile.close()
    >>> testfile.readline()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: I/O operation on closed file.

But you're not getting that error. So, some other reason explains the
lack of output.

 \       “… whoever claims any right that he is unwilling to accord to |
  `\             his fellow-men is dishonest and infamous.” —Robert G. |
_o__)           Ingersoll, _The Liberty of Man, Woman and Child_, 1877 |
Ben Finney

More information about the Tutor mailing list