-2

I'm trying to import some pointcloud coordinates into python, the values are in a text file in this format

0.0054216 0.11349 0.040749   
-0.0017447 0.11425 0.041273  
-0.010661 0.11338 0.040916  
0.026422 0.11499 0.032623

and so on.
Ive tried doing it by 2 methods

def getValue(filename):       
    try:                                                                            
        file = open(filename,'r')  
    except: IOError:  
       print ('problem with file'), filename       
    value = []  
    for line in file:  
        value.append(float(line))  
    return value  

I called the above code in idle but there is an error that says the string cannot be converted to float.

import numpy as np  
import matplotlib.pyplot as plt

data = np.genformtxt('co.txt', delimiter=',')

In this method when I call for data in idle it says data is not defined.

Below is the error message

>>> data[0:4]
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
data[0:4]
NameError: name 'data' is not defined
DavidG
  • 24,279
  • 14
  • 89
  • 82

2 Answers2

0

With the data you provided I would say you are trying to use:

np.loadtxt(<yourtxt.txt>, delimiter=" ")

In this case your delimiter should be blank space as can be seen in you data. This works perfectly for me.

Your problem is you are using the comma as delimiter.

Ivan
  • 782
  • 11
  • 23
0

float() converts one number string, not several (read its docs)

In [32]: line = '0.0054216 0.11349 0.040749 '
In [33]: float(line)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-33-0f93140abeab> in <module>()
----> 1 float(line)

ValueError: could not convert string to float: '0.0054216 0.11349 0.040749 '

Note that the error tells us which string is giving it problems.

It works if we split the line into substrings and convert those individually.

In [34]: [float(x) for x in line.split()]
Out[34]: [0.0054216, 0.11349, 0.040749]

Similarly, genfromtxt needs to split the lines into proper substrings. There aren't any , in your file, so clearly that's the wrong delimiter. The default delimiter is white space, which works just fine in this case.

In [35]: data = np.genfromtxt([line])
In [36]: data
Out[36]: array([0.0054216, 0.11349  , 0.040749 ])

With the wrong delimiter it tries to convert the whole line to a float. It can't (same reason as above), so it uses np.nan instead.

In [37]: data = np.genfromtxt([line], delimiter=',')
In [38]: data
Out[38]: array(nan)
hpaulj
  • 221,503
  • 14
  • 230
  • 353