Skip to main content

14.2) Reading Arrays With NumPy


If your file only contains a simple array, all you need to read it in is:

a= np.genfromtxt(‘array1.txt’)

Download array1.txt and read it with genfromtxt.

You can also read in a file where numbers are delimited with commas (.csv), tab or other:

a=np.genfromtxt(‘array1.csv’, delimiter=",")

Download array1.csv and read it with the command above.

You can skip header lines that describe the file:

a=np.genfromtxt(‘array1.txt’, skip_header=3)

If you’re only interested in a specific column (e.g. the first one):

a=np.genfromtxt(‘array1.txt’, usecols=(0))

You can also write some output to a text file with the savetxt() function:

np.savetxt(‘file.out', a, delimiter=',')