Cache file handle to netCDF files in python
<p>Is there a way to cache python file handles? I have a function which takes a netCDF file path as input, opens it, extracts some data from the netCDF file and closes it. It gets called a lot of times, and the overhead of opening the file each time is high.</p>

<p>How can I make it faster by maybe caching the file handle? Perhaps there is a python library to do this</p>

<p>What about this?</p>

<pre><code>filehandle = None
def get_filehandle(filename):
    if filehandle is None or filehandle.closed():
        filehandle = open(filename, "r")
    return filehandle
</code></pre>

<p>You may want to encapsulate this into a class to prevent other code from messing with the <code>filehandle</code> variable.</p>

python netcdf