Matthew Spahr
Matthew Spahr

Reputation: 105

reading a txt file of String of scientific notation converting to numerical

I have a .txt file I am reading from and it looks something like this:

-1.000000000000000000e+01 4.495406013054247296e+02
-9.933110367892975745e+00 7.574962784496592576e+02
-9.866220735785953266e+00 9.492438285952409842e+02
-9.799331103678929011e+00 1.096930466897883889e+03
...

I am reading this into a 2D array and then putting into separate column arrays. When I do this, I receive an error and am not sure what to do.

with open("hw2_data.txt", "r") as dataFile: 
    data = [line.split() for line in dataFile]
i = 0
x = []
y = []
for line in lines: 
    x.append(int(data[i][0]))
    y.append(data[i][1])
    i = i + 1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-30-b77a8a85fae8> in <module>()
      3 y = []
      4 for line in lines:
----> 5     x.append(int(data[i][0]))
      6     y.append(data[i][1])
      7     i = i + 1

ValueError: invalid literal for int() with base 10: '-1.000000000000000000e+01'

What is the solution to this problem? A few days new to python here and would also appreciate an explanation!

Upvotes: 2

Views: 1727

Answers (1)

AzyCrw4282
AzyCrw4282

Reputation: 7744

The question is solved, but this answer shall update on any users coming here with same problem. The problem is that a ValueError is thrown if you pass a string representation of a float into int, or a string representation of anything but an integer (including empty string). If you do want to pass a string representation of a float to an int, you can convert to a float first, then to an integer:

The code below should show you what's going wrong with your input.

>>> int('5')
5
>>> float('5.0')
5.0
>>> float('5')
5.0
>>> int(5.0)
5
>>> float(5)
5.0
>>> int('5.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
>>> int(float('5.0'))
5

As you've mentioned in the comments then converting into float instead of int would also work, like this.

x.append(float(data[i][0]))

You can read more about it here

Upvotes: 1

Related Questions