could not convert string to float - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: could not convert string to float (/thread-27010.html) |
could not convert string to float - player1681 - May-22-2020 After reading a text file, as a column, I want to convert it from string to float; however, an error appears: with open('posx_mean_no_acoplo_tf_multiple.txt', 'r') as f2: data = f2.read() print(data) data2=float(data) print(type(data2)) Can anybody help me?I am attaching the text file just in case someone wants to take a look Regads. RE: could not convert string to float - ibreeden - May-22-2020 As the message says: data is not a float. And also as the message shows: data is a lot of floats. That is the problem. You have to convert the text lines one by one to float. I guess something like (untested): for dataline in data: print(float(dataline)) RE: could not convert string to float - player1681 - May-22-2020 (May-22-2020, 09:41 AM)ibreeden Wrote: As the message says: data is not a float. And also as the message shows: data is a lot of floats. That is the problem. You have to convert the text lines one by one to float. I guess something like (untested): Thanks for the answer, but I am afraid it doesn't work, since it seems to convert element to element, if the first row is 2.25, float(data[3])=5.0, aditionally, the error appears, probably due to the fact that the code is converting each element by itself to float.EDIT: with open('posx_mean_no_acoplo_tf_multiple.txt', 'r') as f: content = f.readlines() content = [x.strip() for x in content] [float(i) for i in content] print(content) type(content)seems to work RE: could not convert string to float - hussainmujtaba - May-22-2020 with open('a.txt', 'r') as f2: data = f2.read() data=(data.split("\n")) data=[float(i) for i in data] dataWe first convert the string into list by using \n as delimiter. Then convert each element to float RE: could not convert string to float - buran - May-22-2020 with open('posx_mean_no_acoplo_tf_multiple.txt', 'r') as f2: data = [float(line) for line in f2] |