Does Julia automatically close files when their handles go out of scope?

julia

Solution

Yes, that is done automatically. However, finalizers do not get called when an object goes out of scope, but rather when garbage collection determines that there are no more references to that object. This may not happen when you expect or want it to, however. To have file handles automatically closed upon exiting the current scope, you can use the open-do-block construct:

open("file.txt") do fh
  # do stuff with open file handle `fh`
end # `fh` is closed here

Problem

Julia provides open() and close() functions for files. Is something like ``` finalizer(filehandle, obj -> close(obj), filehandle ) ``` automatically implemented when you open a file?

Original source