I am trying to read some numbers from a file and store them into a matrix using Python. In the file, on the first line, I have 2 numbers, n and m, the number of lines and the number of columns and on the next lines, I have n*m values. The complicated part is that in the file, on the second line, for example, I do not have m values, I have only m-2 values. So I cannot read the file one line at a time and just store the values in a matrix. Editing the file is not option because I have files which have 200 rows and 1000 columns. This is how a file with less rows and columns looks:
4 5
1 2 3
4 5 1 2 3 4
5 1 2
3 4 5 1 2
3 4 5
I have managed to resolve this problem by storing all the values in an array and then deleting the first two values, which are n and m, and then creating a matrix from that array.
This is my code:
f = open('somefile2.txt')
numbers = []
for eachLine in f:
line = eachLine.strip()
for x in eachLine.split(' '):
line2 = int(x)
numbers.append(line2)
f.close()
print numbers
n = numbers[0]
del numbers[0]
m = numbers[0]
del numbers[0]
print n, m, numbers
vector = []
matrix = []
for i in range(n):
for j in range(m):
vector.append(numbers[j])
matrix.append(vector)
vector = []
print matrix
This gives me the expected result, but is this the right way to do it, by using the extra array numbers
, or is there an easier way in which I store all the values directly into a matrix?