Does filehandle get closed automatically in Python after it goes out of scope?

file, python, scope

Solution

It should close the file handle in the file's `__del__` statement, but a better approach would be to use a `with` block:

def read_contents(file_path):
  with open(file_path, 'r') as f:
    return f.read()

See http://docs.python.org/library/stdtypes.html#file.close for more information.

Problem

If I do the following, does filehandle get closed automatically as it goes out of scope in Python: ``` def read_contents(file_path): return file(file_path).read() ``` If it doesn't, how can I write this function to close the scope automatically?

Original source