Does a Python "reader" need to be closed?

I’m writing a Python script to serve as the black-box simulation interface driver for a DAKOTA project. Essentially, this Python driver generates a simulation model, submits a solver subprocess which creates a new .vtu file with the hardcoded name: output_ts000001.vtu, which is then read using another method that does:

reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName( "output_ts000001.vtu" )
reader.Update()
output = reader.GetOutput()

I extract out the data I need, compute, then return the objective function. DAKOTA then generates the next iteration / guess and the process starts over. My question is, do I need to close the reader after I finish processing the data? It would seem like the file would be open, and wouldn’t be able to be overwritten or deleted. Yet I’ve been poking around https://kitware.github.io/vtk-examples/site/Python and https://gitlab.kitware.com/vtk/vtk-examples/-/tree/master/src/Python/IO and can’t seem to find any examples that close() a reader. This suggests to me that this isn’t necessary, but that clashes with my general I/O experiences. Is calling del reader sufficient? Is there some documentation I missed that describes why deleting or closing isn’t necessary?

The file stream is destroyed when the reader is destroyed, so there’s no need to close it explicitly.

The reader will close the stream as soon as it finishes reading the data.

In other words, reader.Update() will open the file, read its contents, and then close the file.

1 Like