I can't remove file, created by memmap
<p>I can't remove file created <code>numpy.memmap</code> funtion</p>

<pre><code>class MyClass
 def __init__(self):    
  self.fp = np.memmap(filename, dtype='float32', mode='w+', shape=flushed_chunk_shape)
    ...
 def __del__(self):   
  del self.fp
  os.remove(filename)
</code></pre>

<p>When I run <code>del myclass</code> (instanse of MyClass) I've got error <code>WindowsError: [Error 32] The process cannot access the file</code>. If I use <code>memmap</code> and deleting the file in no objected oriented way everything ok. So I consider trouble in destructor. But why it happens?</p>

<p>Numpy memmapped files are not unmapped until garbage collected, and <code>del self.fp</code> does not ensure garbage collection.  A file which is not unmapped yet cannot be deleted.</p>

<p>The numpy.memmap docs say "Deletion flushes memory changes to disk".  It does not say it unmaps, because it doesn't unmap.</p>

<p>Solution 1.  Force garbage collection </p>

<pre><code>import gc
...
del self.fp
gc.collect()
os.remove(filename)
</code></pre>

<p>You need to make sure there are no other references to fp anywhere, or it may not be garbage collected even in this case.</p>

<p>Solution 2.  Force unmap</p>

<pre><code>self.fp._mmap.close()
del self.fp
os.remove(filename)
</code></pre>

<p>Note that in the second case, if there is an access to fp after it's closed, it will probably crash the python interpreter (not throw exception, just crash)</p>

python numpy numpy-memmap