I have a text file which contains matrix of N * M dimensions.
For example the input.txt file contains the following:
You can do this:
fin = open('input.txt','r')
a=[]
for line in fin.readlines():
a.append( [ int (x) for x in line.split(',') ] )
The following does what you want:
l = []
with open('input.txt', 'r') as f:
for line in f:
line = line.strip()
if len(line) > 0:
l.append(map(int, line.split(',')))
print l
Consider
with open('input.txt', 'r') as f:
l = [[int(num) for num in line.split(',')] for line in f]
print(l)
produces
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 2, 1, 0, 2, 0, 0, 0, 0], [0, 0, 2, 1, 1, 2, 2, 0, 0, 1], [0, 0, 1, 2, 2, 1, 1, 0, 0, 2], [1, 0, 1, 1, 1, 2, 1, 0, 2, 1]]
Note that you have to split on commas.
If you do have blank lines then change
l = [[int(num) for num in line.split(',')] for line in f ]
to
l = [[int(num) for num in line.split(',')] for line in f if line.strip() != "" ]
You should not write your csv parser, consider the csv
module when reading such files and use the with
statement to close after reading:
import csv
with open('input.txt') ad f:
data = [map(int, row) for row in csv.reader(f)]
import numpy as np
f = open ( 'input.txt' , 'r')
l = []
l = np.array([ line.split() for line in f])
print (l)
type(l)
output:
[['0'] ['0'] ['0'] ['0,0,0,0,0,0,0,0,0,0,0'] ['0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'] ['0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0']]
numpy.ndarray
Check out this small one line code for reading matrix,
matrix = [[input() for x in range(3)] for y in range(3)]
this code will read matrix of order 3*3.