Phorce
Phorce

Reputation: 4652

Python Numpy array reading from text file to 2D array

I have a text file and that contains the following:

-11.3815 -14.552 -15.7591 -18.5273 -14.6479 -12.7006 -13.9164 -19.8172 -22.951 -16.5832 
-16.555 -17.6044 -15.9577 -15.3363 -17.7223 -18.9881 -22.3789 -24.4881 -16.6685 -17.9475 
-18.2015 -15.2949 -15.5407 -18.8215 -24.5371 -17.0939 -15.3251 -13.1195 -13.3332 -19.3353 
-14.6149 -14.5243 -15.1842 -15.5911 -14.3217 -15.4211

With a lot more data inside of this. I want to read this inside a 2D array. I have tried the following:

with open('test.txt') as file:
     array2d = [[float(digit) for digit in line.strip()] for line in file]

And just seem to be getting:

ValueError: could not convert string to float: -

Any idea how to solve this problem?

Upvotes: 2

Views: 15417

Answers (1)

Christian Tapia
Christian Tapia

Reputation: 34176

You must use

split()

instead of

strip()

because strip() returns a string, so you are iterating over each character of that string. split() return a list, that's what you need. Read more in Python docs.

Code:

with open('sample.txt') as file:
    array2d = [[float(digit) for digit in line.split()] for line in file]

print array2d

Output:

[[-11.3815, -14.552, -15.7591, -18.5273, -14.6479, -12.7006, -13.9164, -19.8172, -22.951, -16.5832], [-16.555, -17.6044, -15.9577, -15.3363, -17.7223, -18.9881, -22.3789, -24.4881, -16.6685, -17.9475], [-18.2015, -15.2949, -15.5407, -18.8215, -24.5371, -17.0939, -15.3251, -13.1195, -13.3332, -19.3353], [-14.6149, -14.5243, -15.1842, -15.5911, -14.3217, -15.4211]]

Upvotes: 9

Related Questions