Search code examples
pythonnumpymatrixtext-filesbinary-data

Reading matrix from a text file and storing it in an array


Defintion

I have the following matrix stored in a text file:

 1 0 0 1 0 1 1
 0 1 0 1 1 1 0
 0 0 1 0 1 1 1

I want to read this matrix from the text tile and store it in a 2D array using python 2.7.

Code I attempted

The code I attempted is as follows:

f = open('Matrix.txt')
triplets=f.read().split()
for i in range(0,len(triplets)): triplets[i]=triplets[i].split(',')
A = np.array(triplets, dtype=np.uint8)

print(A)

Problem

As it stands the code above is printing the matrix in a 1D manner. Is it possible to save the matrix in a 2D manner as defined in the matrix above?


Solution

  • Use np.loadtxt:

    A = np.loadtxt('filename.txt')
    
    >>> A
    array([[ 1.,  0.,  0.,  1.,  0.,  1.,  1.],
           [ 0.,  1.,  0.,  1.,  1.,  1.,  0.],
           [ 0.,  0.,  1.,  0.,  1.,  1.,  1.]])
    

    Alternatively, you could read it line by line similarly to what you were doing (but this isn't efficient):

    A = []
    with open('filename.txt', 'r') as f:
        for line in f:
            A.append(list(map(int,line.split())))
    
    >>> np.array(A)
    array([[1, 0, 0, 1, 0, 1, 1],
           [0, 1, 0, 1, 1, 1, 0],
           [0, 0, 1, 0, 1, 1, 1]])