deltascience
deltascience

Reputation: 3380

How to read a cell from matrix in a file

I have a huge matrix that I saved with savetxt with numpy library. Now I want to read a single cell from that matrix e.g

cell = getCell(i,j)
print cell 

>> return the value : 10 for example

I tried this :

x = np.loadtxt("fname.m",dtype="int",usecols=([i]))
cell=x[j]

but it is really slow because I loop over many index. Is there a way to do that without reading useless lines ?

Upvotes: 1

Views: 81

Answers (1)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58895

One way to go is to exhaust a file iterator until the line you want:

with open('fname.m') as f:
    for _ in range(i):
         line = f.next()
    cell = line.split()[j]

Upvotes: 1

Related Questions