Let's assume I have a file test.txt
and want to print the contents. I could do it like this in Python (this is just an example to illustrate my question, not an example of good code):
for i in (line for line in open('test.txt')):
print ">", i,
I used strace
to make sure that the file is opened and closed after the code has executed.
The question: Why is the file closed? I guess it has something to do with context managers, but I can't find any reference to this kind of construct and why the file gets automatically closed. Who knows what happens exactly behind the scenes and can explain it?