I've made a function that reads a file and separates the first line from the rest.
The two files which I'm using for this are aaa.txt and bbb.txt. I try to manipulate the data. I tried squaring each element of each string but I realize that I need to float it but I'm not sure why it won't just float. Where did I went wrong?
aaa.txt is below
test a line 1
3,6,8,99,-4,0.6,8
0,9,7,5,7,9,5
2,2,2,2,2,2,5
7,5,1,2,12,8,0.9
=====================
bbb.txt is as below
test b line 1
1,2,3,4,5,6,7,8
55,0,90,09,1,2,3,
8,9,7,6,8,7,6
3,43,5,8,2,4,1
======================
def mi_func(P):
f=open(P, 'r')
first = f.readline()
restlines= f.readlines()
f.close()
return first, restlines
afirst,arest = mi_func('aaa.txt')
bfirst,brest = mi_func('bbb.txt')
print(arest)
print(brest)
##################
#convert a rest into a float here
#convert b rest into a float here
#################
for i in range(len(arest)):
arest[i] = [float(x) for x in arest[i].strip().split(',')]
for i in range(len(brest)):
brest[i] = [float(x) for x in brest[i].strip().split(',')]
p=[i**2 for i in arest] #square each element of a rest
c=[i**2 for i in brest] #square each element of b rest
print(p)
print(c)
['3,6,8,99,-4,0.6,8\n', '0,9,7,5,7,9,5\n', '2,2,2,2,2,2,5\n', '7,5,1,2,12,8,0.9\n']
['1,2,3,4,5,6,7,8\n', '55,0,90,09,1,2,3,\n', '8,9,7,6,8,7,6\n', '3,43,5,8,2,4,1']
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-1-36603657d444> in <module>()
21
22 for i in range(len(brest)):
---> 23 brest[i] = [float(x) for x in brest[i].strip().split(',')]
24
25
<ipython-input-1-36603657d444> in <listcomp>(.0)
21
22 for i in range(len(brest)):
---> 23 brest[i] = [float(x) for x in brest[i].strip().split(',')]
24
25
ValueError: could not convert string to float:
bbb.txtyou've55,0,90,09,1,2,3,notice the,in the end, your code tries to dofloat('')which is failing.