Reputation:
I am trying to load some data from a text file, but keep on getting this error:
def getData(file):
f = open('N_20_T_10.txt','r')
x, y, z = [], [], []
f.readline()
for line in f:
xp, yp, zp = line.split(' ')
x.append(float(xp))
y.append(float(yp))
z.append(float(zp))
f.close()
return x, y, z
def plotData(inputFile):
x, y, z = getData(inputFile)
x = pylab.array(x)
y = pylab.array(y)
z = pylab.array(z)
N = np.linspace(1, 100, 100)
r = np.sqrt(x**2 + y**2+z**2)
mean_r = N*r
data = np.column_stack(N)
data1 = np.column_stack(mean_r)
print(data, mean_r)
#print(N, r)
np.savetxt('new.txt', list(zip(N, mean_r)), fmt='%.1f', delimiter=",")
pylab.plot(N, mean_r)
pylab.xlabel('N')
pylab.show()
plotData('N_20_T_10.txt.txt')
Here is the data I'm using. I think it keeps on coming maybe because of some extra whitespaces in the data, because when I use a different file with no spaces it works well. But I'm not sure.
Upvotes: 0
Views: 77
Reputation: 4497
From the picture it seems before the first number there is a space. Then you will get back 4 elements of the split(' ')
operation . See the following example:
numbers = " 1 2 3"
numbers.split(' ')
# output: ['','1', '2', '3']
You can solve your problem by skipping the first element of the array as follows:
numbers.split(' ')[1:]
# output: ['1', '2', '3']
or using strip()
:
numbers.strip().split(' ')
# output: ['1', '2', '3']
or you can simply use split()
without a parameter:
numbers.split()
# output: ['1', '2', '3']
So in your case, the following code should work:
xp, yp, zp = line.spilt()
Upvotes: 1
Reputation: 4366
If this is whitespace problem then you can solve it using split without defining separator. Split docs explain:
If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator ...
and example
>>> ' 1 2 3 '.split()
['1', '2', '3']
Upvotes: 1
Reputation: 1680
I would try to strip all whitespaces at the beginning and the end of each line by using
xp, yp, zp = line.strip().split(' ')
Upvotes: 1