14.1) Reading Arrays - revision
In previous sections we described how to read a dataset from a text file. If you want to read a 2D array from a text file using the file methods, you have to do something like this:
import NumPy as np nrows=12 ncols=4 a = np.empty((nrows,ncols)) # create an array knowing its size a[:]=np.NaN # fill the array with NaN f=open('array1.txt', 'r') for row in range(nrows): values=f.readline().split() # read line and split columns for col in range(len(values)): # loop over columns a[row,col]=float(values[col]) # populate array print a
You could determine the number of rows and columns from the file, but that would make the program even more complex. Luckily, NumPy has some great functions to easily read in an array from a file and it can even handle missing values.