Search code examples
numpynumpy-memmap

What is wrong with this numpy memmap create / save / load, it doesn't seem to save


I start by creating a memmap, loading some random numbers, and deleting it in order to save it to file:

db = np.memmap('/content/drive/My Drive/Share/DBs/test.npy', mode='w+', shape = (5,5))
db = np.random.uniform(size = (5,5))
print(db)
del db

Output:
[[0.601 0.776 0.566 0.288 0.985]
 [0.425 0.381 0.854 0.402 0.894]
 [0.242 0.143 0.102 0.702 0.427]
 [0.137 0.348 0.493 0.959 0.658]
 [0.158 0.023 0.267 0.469 0.352]]

Then when I go to load it again, I just get zeros:

db2 = np.memmap('/content/drive/My Drive/Share/DBs/test.npy', mode='r', shape = (5,5))
print(db2)

Output:
[[0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]
 [0 0 0 0 0]]

FOr some reason its not saving the random numbers? I am using Google Colab.


Solution

  • I changed this line: db = np.random.uniform(size = (5,5)) to this: db[:] = np.random.uniform(size = (5,5)) and now it works. I guess it was because instead of adding data to the memmap I was completely overwriting it with a regular numpy array?