2

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?

1
  • The number of elements in each row is not a constant in your file. You can't get a numpy array from such data. Commented Jan 5, 2014 at 1:34

1 Answer 1

9

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

Hey, thanks! Is there a way to tell if an array is 2D or 3D inside of python? I.e. "The array is 2D"

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.