何时/如何匿名文件对象关闭? [英] When/How does an anonymous file object close?
问题描述
在这个问题关于一个python单线程,它发生在我身上我不知道python如何处理匿名文件对象。从问题:
pre $ open(to_file,'w')。write(open(from_file).read())
有两个调用打开
而不使用与
关键字(这通常是我如何处理文件)。过去我曾使用过这种未命名的文件。 IIRC,似乎有一个剩余的操作系统级别的文件锁定,将在一两分钟后过期。
那么这些文件句柄会发生什么?他们是通过垃圾收集清理吗?由操作系统?当 close()
被调用时,Python机器和文件会发生什么情况,当脚本结束并经过一段时间后,它会发生什么?
但是,由于垃圾收集器必须执行,所以无法保证。在测试中,我已经做过,每次都会一次关闭。
语句的 所以,你的单行程式变成: *除非你像 In the comments of this question about a python one-liner, it occurred to me I have no idea how python handles anonymous file objects. From the question: There are two calls to So what happens to these file handles? Are they cleaned up by garbage collection? By the OS? What happens to the Python machine and file when Monitoring the file descriptor on Linux (by checking /proc/$$/fds) and the File Handle on Windows (using SysInternals tools) it appears that the file is closed immediately after the statement. This cannot be guarenteed however, since the garbage collector has to execute. In the testing I have done it does get closed at once every time. The So your one-liner becomes: The advantage of * Unless you do something like 这篇关于何时/如何匿名文件对象关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!推荐为与
打开
一起使用,但实际需要的场合很少见。很难证明你必须使用和
的情况,但是安全可能是个好主意。
with open(to_file ,'w')作为tof,打开(from_file)作为fof:
tof.write(fof.read())
与
的优点在于,特殊的方法(在io类中)称为 __ exit __()
os._exit()
那样做。 open(to_file, 'w').write(open(from_file).read())
open
without using the with
keyword (which is usually how I handle files). I have, in the past, used this kind of unnamed file. IIRC, it seemed there was a leftover OS-level lock on the file that would expire after a minute or two.close()
is called, and will it all happen anyway when the script finishes and some time passes?with
statement is recommended to be used with open
, however the occasions when it is actually needed are rare. It is difficult to demonstrate a scenario where you must use with
, but it is probably a good idea to be safe. with open(to_file, 'w') as tof, open(from_file) as fof:
tof.write(fof.read())
with
is that the special method (in the io class) called __exit__()
is guaranteed* to be called.os._exit()
.