Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to close the file in json.load?

Tags:

python

json

file

It's clear that a file object should be closed to delete it from memory:

file = open('data.txt', 'r')
#more code here
file.close()

Is it also necessary to close a file object served to the json.load method?

data = json.load(open('data.json','r'))

I guess no since the file object not stored in a variable, but if yes, how can it be done?

like image 784
multigoodverse Avatar asked Dec 04 '17 11:12

multigoodverse


People also ask

How do I close a JSON file?

Use json. load(file) to read a JSON fileCall file. close() to close the file.

What is JSON load used for?

The json. load() is used to read the JSON document from file and The json. loads() is used to convert the JSON String document into the Python dictionary. fp file pointer used to read a text file, binary file or a JSON file that contains a JSON document.

Does JSON loads preserve order?

Both JSON en Python dictionaries (those are JSON objects) are unordered. So in fact it does not makes any sense to do that, because the JSON encoder can change the order. This will thus store the items in an OrderedDict instead of a dictionary.

What is the difference between JSON loads and dumps?

loads() takes in a string and returns a json object. json. dumps() takes in a json object and returns a string.


1 Answers

Don't rely on the GC to clean/close the file descriptor. Use a context manager instead.

You also don't need to provide the mode 'r' since it is the default for open.

with open('data.json') as f:
    data = json.load(f)
like image 156
DeepSpace Avatar answered Sep 17 '22 22:09

DeepSpace