1

Will a single call to open() without assigning it to a variable close the file handle after it is done executing?

import json
_keyfile = json.load(open("s3_key.json", "r"))

What about if you call .read() on it?

import json
_keyfile = json.loads(open("s3_key.json", "r").read())
mevers303
  • 442
  • 3
  • 10
  • 2
    This is not specified. For CPython, it will usually close as soon as it isn't needed anymore, other implementations may do it later or the OS does it when application terminates. The call to `read()` usually doesn't matter here. – Michael Butscher Nov 04 '18 at 23:12
  • 2
    https://stackoverflow.com/questions/1834556/does-a-file-object-automatically-close-when-its-reference-count-hits-zero – Klemen Tusar Nov 04 '18 at 23:15

1 Answers1

5

As per the python docs, the file remains open until you call close() on the file object or the garbage collector kicks in and closes it for you.

Because of this, prefer to use context managers (i.e. the with statement) when reading files, as they will close the file for you.

import json
with open("s3_key.json", "r") as f:
    _keyfile = json.load(f)
# f is now closed
Chris Beard
  • 191
  • 9