Read matrix from txt file in Python (no numpy) using function
Question:
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 1n":
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')
Answers:
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 1n":
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')
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 1n":
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 1n":
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')