Opening and closing a file in python

I read that when a file is opened using the format below

with open(filename) as f: #My Code f.close() 

Explicit file closing is not required. Can someone explain why this is so? Also, if someone explicitly closes the file, will it have any undesirable effect?

+4
source share
2 answers

Overview: this is when: When you leave a nested block, Python automatically calls f.close() for you.

It doesn’t matter if you just go down from the bottom or call break / continue / return to jump out of it or raise an exception; no matter how you leave this block. He always knows that you are leaving, so he always closes the file. *


One level down, you can think of it as a mapping to a try: / finally: try: :

 f = open(filename) try: # My Code finally: f.close() 

One level down: how does he know to call close instead of something else?

Well, actually it is not. He actually calls the special methods __enter__ and __exit__ :

 f = open() f.__enter__() try: # My Code finally: f.__exit__() 

And the object returned by open (a file in Python 2, one of the wrappers in io in Python 3), has something like this in it:

 def __exit__(self): self.close() 

This is actually a little more complicated than the latest version, which simplifies the creation of more efficient error messages and allows Python to avoid "entering" a block that does not know how to "exit".

To understand all the details, read PEP 343 .


Also, if someone explicitly closes the file, will it have any undesirable effect?

In general, this is bad.

However, file objects are not suitable to make them safe. It is a mistake to do anything to a closed file except close again.


* If you do not leave, say by pulling the power cord on the server in the middle of it, executing your script. In this case, obviously, any code never runs, much less close . But explicit close unlikely to help you there.

+12
source

Closing is not required because the with statement automatically does this.

In the with statement, the __enter__ method is __enter__ on open(...) , and as soon as you exit this block, the __exit__ method is called.

Thus, closing it manually is simply useless, as the __exit__ method __exit__ automatically take care of this.

As for f.close() after, it is not, but it is useless. It is already closed, so it won’t do anything.

Also see this blog post for more information on the with statement: http://effbot.org/zone/python-with-statement.htm

+3
source

Source: https://habr.com/ru/post/1489598/


All Articles