Question

Hi so essentially I have the basic text file:

3
1 0 1
0 1 0
1 1 1

And I'm trying to create a 2 dimensional array that contains the values as integers.
My code so far is:

import numpy as np
f = open('perc.txt', 'r')
n = f.readline()
j = 0
dim = int(n.rstrip(' \n'))
mat = np.zeros((dim, dim))
for i in range(dim):
    n = f.readline()
    line = n.rstrip(' \n')
    line = line.split()
    line = map(int,line)
    while j < dim: 
        mat[i][j] = line[j]
        j += 1

But when I run the code, the result is:

1 0 1
0 0 0
0 0 0

yet line is currently the array[(1, 1, 1)] so clearly that part of the iteration is working correctly. How can I get the matrix to update values properly.

Was it helpful?

Solution

Use

with open(...) as outfile:
    #outfile.write()
    #outfile.read()
    #outfile.readlines()
    #etc

to have the file automatically close for you. It looks better and you don't have to remember to close the file.

I just read the whole thing in and split the string into a list. Then I used the indices to create the array.

arr = np.array([lines[1:]) creates a flat array of each element in lines starting at the 2nd element, so I resized it using the dim x dim you provided with the resize function.

import numpy as np

lines = []

with open('perc.txt', 'r') as outfile:
    lines = outfile.read().split()

>>> print lines
>>> ['3', '1', '0', '1', '0', '1', '0', '1', '1', '1']

arr = np.array([lines[1:]])

dim = int(lines[0])

arr.resize(dim, dim)

>>> print arr
>>> [['1' '0' '1']
     ['0' '1' '0']
     ['1' '1' '1']]

OTHER TIPS

You need to reset j to zero before the while loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top