Reading and writing files

numpy has many function to read and write files from/to disk.


In [ ]:
import numpy as np

Single array, binary format


In [ ]:
a = np.random.rand(20)
a

Save the array to a binary file named a.npy:


In [ ]:
np.save('a', a)

In [ ]:
ls

Load the array back into memory:


In [ ]:
a_copy = np.load('a.npy')

In [ ]:
a_copy

Single array, text format


In [ ]:
b = np.random.randint(0, 10, (5,3))
b

The savetxt function saves arrays in a simple, textual format that is less effecient, but easier for other languges to read:


In [ ]:
np.savetxt('b.txt', b)

In [ ]:
ls

Now you could open the file b.txt and see the contents. We can also use loadtxt to read the contents of the file.


In [ ]:
np.loadtxt('b.txt')

In [ ]: