Is a file automatically closed if it is read on the same line as the opening?

If I do (in Python):

text = open("filename").read()

- is the file automatically closed?

+4
source share
3 answers

The garbage collector will be activated at some point, but you cannot be sure when you will not click it.

The best way to make sure the file is closed when you exit the scope is to simply do this:

with open("filename") as f: text = f.read()

also single line, but more secure.

+6
source

In CPython (the reference Python implementation), the file will be automatically closed. CPython destroys objects as soon as they have no references, which happens at the end of an instruction at the very end.

Python , - (. PyParallel ).

Python - , . with, , , .

, , .

+3

, CPython , . , , , with open(...) .

+2

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


All Articles