Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will passing open() as json.load() parameter leave the file handle open?

Tags:

python

json

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)

or

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"))

The docs say that json.load() is expecting a .read()-supporting file-like object containing a JSON document.

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?

like image 965
Alexander Avatar asked Mar 12 '14 10:03

Alexander


People also ask

What does JSON load () do?

load() json. load() takes a file object and returns the json object. It is used to read JSON encoded data from a file and convert it into a Python dictionary and deserialize a file itself i.e. it accepts a file object.

What does JSON loads () return?

load or json. loads() method, it returns a Python dictionary. If you want to convert JSON into a custom Python object then we can write a custom JSON decoder and pass it to the json. loads() method so we can get a custom Class object instead of a dictionary.

What does JSON () do in Python?

json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.

What is the output of JSON loads?

json. load() takes a file object and returns the json object. A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types.


1 Answers

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.

like image 192
Slawek Rewaj Avatar answered Oct 13 '22 00:10

Slawek Rewaj