Hello Everyone, I want to load the data I have in a file, which looks like:
JavaScript
x
21.4,0.266667,0,0.966667,0.166667,0.966667,0.533333,0.1,
Now, I want to load this from the file and compute the normalization. I do:
JavaScript
f = open("Input.txt", "r")
data = [line.strip() for line in f]
print data
norm = [float(i)/sum(data) for i in data]
print norm
But, I am getting the error:
JavaScript
ValueError: invalid literal for float()
Although, I do the process directly into python 2.7 console in linux like,
JavaScript
a = [21.4,0.266667,0,0.966667,0.166667,0.966667,0.533333,0.1]
norm = [float(i)/sum(a) for i in a]
print norm
This works fine. I don’t know what I am doing wrong. Please help me and I am new to programming. Thanks in advance!
Advertisement
Answer
You need to convert the strings in the file to floats first.
JavaScript
data = []
with open('Input.txt') as f:
for line in f:
data.extend([float(x) for x in line.split(',')])
norm = [x/sum(data) for x in data]