When / How does an anonymous object close?

In the comments, this question about one python slot occurred to me, I have no idea how python handles anonymous file objects. From the question:

open(to_file, 'w').write(open(from_file).read())

There are two calls openwithout using a keyword with(as a rule, I process files). In the past, I used this kind of unnamed file. IIRC, it seemed that there was a residual lock at the OS level in the file, which expires in a minute or two.

So what happens to these file descriptors? Do they clean the wastebasket? Under the OS? What happens to the machine and the Python file when invoked close(), and does it all happen when the script ends and for some time?

+4
source share
2 answers

Monitoring the file descriptor on Linux (by checking / proc / $$ / fds) and the file descriptor on Windows (using the SysInternals tools), it seems that the file closes immediately after the instruction.

This cannot be guaranteed, as the garbage collector must execute. In the testing I did, it closes every time.

The operator is withrecommended to be used with open, however, cases when it is really necessary are rare. It's hard to demonstrate a scenario in which you should use it with, but it's probably nice to be safe.

So your single line font will look like this:

with open(to_file, 'w') as tof, open(from_file) as fof:
    tof.write(fof.read())

with , ( io), __exit__(), *, .

* - os._exit().

+4

, CPython , , .

, , , with ( 2.5, from __future__ import with_statement).

+1

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


All Articles