Home > OS >  How to load a txt file into 2d matrix?
How to load a txt file into 2d matrix?

Time:10-22

I am fairly need to Python and need some help. I am trying to load a txt file and store it as a variable, N where N is supposed to be a square matrix. However, when I tried to check, the ndim() of N is 1 and the number of columns is not equal the number of rows.

I tried the following codes:

N = open('Graph2021.txt', 'r').readlines()
N = np.array(M)

Could someone please help. I have attached a screenshot of part of the txt file to show the breakage of the code to separate the columns (I think).

txt file is filled with zeros and ones:

txt file

CodePudding user response:

import numpy as np

N_lines = open('Graph2021.txt', 'r').readlines()
N_matrixlist = [list(map(float,i.strip().split(','))) for i in N_lines]
N = np.array(N_matrixlist)

CodePudding user response:

You're reading a file as a list with each element to be a line. However by what you described each line has N element. And surely it must be separated by something (A white space, comma, etc). You have to split your each line by that separator.

with open('Graph2021.txt', 'r') as the_file:
    M = []
    for each_line in the_file:
        M.append(each_line.split(",")) # , is separator...
    N = np.array(M)

More pythonic way:

with open('Graph2021.txt', 'r') as the_file:
    N = np.array([each_line.split(",") for each_line in the_file]) # , is separator...
  
  • Related