OultimoCoder - 4 months ago 22

Python Question

If I have a text file where each line is a line in a matrix and each matrix is separated by a new line e.g.

1234

1234

2345

2345

How would I go about creating an array of those matrices (Without using numpy).

For 1 matrix I do:

`with open("matrix.txt", "r") as file:`

matrix=[line.split() for line in file]

To extrapolate this code for multiple matrices I tried doing:

`x=0`

matrix=[]

with open("matrix.txt", "r") as file:

for line in file:

if line == "\n":

x+=1

else:

matrix[x].append([line.split()])

print(matrix)

Where the line from a textfile gets appended to a matrix like before but if it encounters a newline it appends the next lines to the next index of the 3d array so I end up with an array of arrays.

The code I have listed gives me and out of index error which I know should happen because when I increase the matrix index with x it doesn't actually exist as I have never created it.

I am stuck and could do with some help. Please ask if you need me to clarify something or if I haven't explained something well enough. Thanks!

Edit: Output would look something like [[[1,2,3,4], [1,2,3,4]], [[2,3,4,5],[2,3,4,5]]]

So matrix[0][1][2] would access the first matrix and retrieve 3.

Answer

Ok, try this::

```
x=0
matrix=[]
row = []
with open("matrix.txt", "r") as file:
for line in file:
line = line.strip("\n")
if line == "":
matrix.append(row)
row = []
else:
row.append([int(x) for x in list(line)])
if (len(row) > 0):
matrix.append(row)
print(matrix)
```

Result: [[[1, 2, 3, 4], [1, 2, 3, 4]], [[2, 3, 4, 5], [2, 3, 4, 5]]]