h5py 文件上下文管理器会自动关闭文件吗?

Hon*_*ear 5 python contextmanager h5py

我已经使用了f = h5py.File(filename, 'r')一段时间了,f.close()最​​后需要用 来关闭。

最近我发现我可以这样做:

with h5py.File(filename, 'r') as f:
     # code to manipulate the file
Run Code Online (Sandbox Code Playgroud)

但是我不确定:这个“上下文管理器”(他们在页面上称之为)是否会自动关闭文件,还是我仍然需要f.close()在最后添加?

我试图在文档中找到答案,但上下文管理器仅在快速入门指南中的一行中提到,显然没有关于它的更多信息。

小智 5

答案是:是的,上下文管理器会自动关闭文件。