1
from numpy import *

f = open('matrix.txt', 'r')

x = []
for line in f.readlines():
    y = [value for value in line.split()]
    x.append(y)

f.close()

x = map(int, x)

a = array([x])

Basically, my code is suppose to open the text file and put it into the list x. I then change those values in x into an integer and place that in an array a. Is there a faster way to do this? Btw my code doesn't work.

2
  • What is in the file? Does it contain multiple lines? Commented Nov 27, 2012 at 6:04
  • Yeah just multiple lines with numbers spaced out, only numbers, no other characters Commented Nov 27, 2012 at 6:19

3 Answers 3

1
import numpy as np
with open('matrix.txt', 'r') as f:
    x = []
    for line in f:
        x.append(map(int, line.split()))
print x
print np.array(x)

With matrix.txt containing 3 lines with 4 numbers each:

1 2 3 4
5 6 7 8
9 8 7 6

as above, this prints

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 8, 7, 6]]
[[1 2 3 4]
 [5 6 7 8]
 [9 8 7 6]]

However, as mentioned in a previous answer, consider using numpy.loadtxt. For example, if
print np.loadtxt('matrix.txt')
is added to the program, it also prints out

[[ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 9.  8.  7.  6.]]
Sign up to request clarification or add additional context in comments.

3 Comments

does that just automatically convert it into an array?
I'm pretty sure you could even specify dtype when you pass it to np.loadtxt to retrieve integers as it appears that is what OP wants.
@mgilson, yes, either of the following produces the matrix with integers: print np.loadtxt('matrix.txt', int) or print np.loadtxt('matrix.txt', dtype=int) (after saying import numpy as np)
1

You'll probably do a little better if you use np.loadtxt.

Comments

0

almost there...

the following lines create a list of list which you don't want

y = [value for value in line.split()]
x.append(y)

because of this the map call would fail

instead of these 2 lines use

x = [int(value) for value in line.split()]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.