将open()作为json.load()参数传递会使文件句柄保持打开状态吗? [英] Will passing open() as json.load() parameter leave the file handle open?

查看:801
本文介绍了将open()作为json.load()参数传递会使文件句柄保持打开状态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个小型Web应用程序,对于每个请求,我都应该打开并读取一个JSON文件.为此,我正在使用 pickledb . 我担心的是,库将open()用作json.load()函数的参数.所以它让我开始思考..

I have written a small web application, and with each request I should open and read a JSON file. I am using pickledb for this purpose. What concerns me about it, is that the library passes open() as a parameter for the json.load() function . So it got me thinking ..

当我编写这样的代码时:

When I write code like this:

with open("filename.json", "rb") as json_data:
    my_data = json.load(json_data)

json_data = open("filename.json", "rb")
my_data = json.load(json_data)
json_data.close()

我非常确定文件句柄已关闭.

I am pretty sure that the file handle is being closed.

但是当我以这种方式打开它时:

But when I open it this way :

my_data = json.load(open("filename.json", "rb"))

文档表示json.load()预期支持.read()的包含JSON文档的类似文件的对象.

问题是,此句柄会保持打开状态,并在每次请求时占用更多内存吗?在这种情况下,谁负责关闭手柄?

So the question is, will this handle stay open and eat more memory with each request? Who is responsible for closing the handle in that case?

推荐答案

对象销毁时将调用文件的Close方法,因为json.load期望输入对象仅读取方法.

Close method of the file will be called when object is destroyed, as json.load expects only read method on input object.

随后发生的事情取决于垃圾回收的实现.您可以在显式关闭文件重要吗?

What happens depends on garbage collection implementation then. You can read more in Is explicitly closing files important?

通常来说,关闭文件是个好习惯.

Generally speaking it's a good practice to take care of closing the file.

这篇关于将open()作为json.load()参数传递会使文件句柄保持打开状态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆