0

I'm trying to read in a text file and format it correctly in a numpy array.

The Input.txt file contains:

 point_load, 3, -300

 point_load, 6.5, 500

 point_moment, 6.5, 3000  

I want to produce this array:

 point_load = [3, -300, 65, 500]

My code is:

 a = []
 for line in open("Input.txt"):
     li=line.strip()
     if li.startswith("point_load")
          a.append(li.split(","))

 #np.flatten(a)

My code prints:

 [['point_load', '     3', '          -300'], ['point_load', '     6.5', '         500']]

Any help would be appreciated. Thank you.

user2845180
  • 33
  • 1
  • 4

3 Answers3

0

Change this line :

a.append(li.split(","))

to this:

a.append(li.split(",")[1:])
Dat Ha
  • 562
  • 1
  • 9
  • 16
0

To end up with a list of numbers instead of strings, I recommend the following:

a = []
for line in open("Input.txt"):
    li=line.strip()
    if li.startswith("point_load"):
        l = li.split(',')
        for num in l[1:]:
            try:
                num = float(num.strip())
                a.append(num)
            except ValueError:
                print 'num was not a number'

The difference here is the list slice which takes the entire line starting from the second comma-separated element (more here: understanding-pythons-slice-notation)

l[1:]

Also, stripping then converting the strings to floats (since you have decimals)

num = float(num.strip())

Resulting array:

a = [3.0, -300.0, 6.5, 500.0]
ma22
  • 46
  • 1
  • 4
  • When running this, sometimes I get the error ValueError: could not convert string to float: 'end'. After searching, I cant find much on this. Any idea what could be causing this? – user2845180 Nov 08 '17 at 22:54
  • This means the string it is trying to convert to float is not actually composed of digits. You could place this conversion in a try-except (I edited the code snippet) – ma22 Nov 09 '17 at 15:16
0
li.split(",")

returns a list, so you appended a list, obtaining a nested list.

You wanted append individual elements append to the a list, namely 2nd and 3rd, i. e. with indices 1 and 2. So instead

a.append(li.split(","))

use

temp = li.split(","))
second = temp[1]
third  = temp[2]
a.append(float(second))
a.append(float(third))

Note the use of the float() function as the .split() method returns a list of strings.
(Maybe in the last .append() would be more appropriate for you the use of int() function instead.)

MarianD
  • 13,096
  • 12
  • 42
  • 54