简体   繁体   中英

Read matrix from txt file in Python (no numpy) using function

I am beginner and trying to Read a matrix from a text file and return it and use function read_matrix(pathname) but all that I can find and build it and it does not work. Can you help me understand where I did wrong. Please no numpy

def read_matrix(pathname):
matrices=[]
m=[]
for line in file("matrix.txt",'r'):
   if line=="1 1\n": 
      if len(m)>0: matrices.append(m)
      m=[]
   else:
      m.append(line.strip().split(' '))
if len(m)>0: matrices.append(m)
return(m)
m = read_matrix('matrix.txt') 

if your file looks like this:

data.txt:

1 2 3
4 5 6
7 8 9

you can read it to a matrix (list of lists) as follow:

with open("data.txt") as fid:
    txt=fid.read()


matrix = [[int(val) for val in line.split()] for line in txt.split('\n') if line]

your code could work as follow, however there are some lines which could be written better:

def read_matrix(pathname):
    matrices = []
    m = []
    for line in open(pathname,'r'):
        if line=="1 1\n": 
            if len(m) > 0: 
                matrices.append(m)
                m=[]
        else:
            m.append(line.strip().split(' '))
    if len(m)>0: matrices.append(m)
    return(m)

m = read_matrix('data.txt')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM