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

Peter Otten __peter__ at web.de
Sat Jan 14 04:45:05 EST 2017


ZEMMOURA Khalil Zakaria wrote:

> Hi,
> 
> I am playing with python3.6 and i noticed a change in the behaviour of the
> open() builtin function.
> 
> The file opened using open() is closed automaticaly after iterationg over
> it in the python shell
> 
> Here is the dummy code i am using:
> 
> # Beggin
> 
> testfile = open('test.txt')
> for line in testfile:
>     print(line)
> 
> # End
> 
> 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.

That is not new. The file is not closed, you have just reached the end of it

>>> f = open("tmp.txt")
>>> for line in f: print(line, end="")
... 
alpha
beta
gamma
>>> for line in f: print(line, end="")
... 
>>>

You can move the file pointer with seek:

>>> f.seek(0)
0
>>> for line in f: print(line, end="")
... 
alpha
beta
gamma

> 
> when i type:
> 
> testfile.close and press the tab key to autocomplete:
> 
> here is what i get
>>>> testfile.close( testfile.closed

There is an attribute "closed" that tells you the state of the file and a 
close() method that closes an open file and does nothing if the file is 
already closed:

>>> f.close()
>>> f.closed
True
>>> f.close()

When you try to iterate over a closed file an exception is raised:

>>> for line in f: print(line, end="")
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.


> when i run that commande and ignore the message:
> testfile.close()
> nothing is prined on the terminal, and python runs the commande as if the
> file is still opened.

I doubt that.
 
> i searched in the doc and this behaviour is not documented.

The documentation is not as concise as one might wish. Have a look at 
<https://docs.python.org/dev/library/io.html>.

> I don't now if it is a bug or i didn't search in the right place.

No bug.



More information about the Tutor mailing list