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?
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)
For me closing a json file works like normal file handling in python.
filename.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.