I'm trying to take floats from a file and place them in an array. Each float has its own line. I'm somewhat new to Python (not the concept I'm trying to execute), and it's not working quite in the way I'd expect.
from array import array
def read_file(infilename):
infile = open(infilename, 'r')
array('f')
for line in infile:
array.append(line)
def main():
filename = "randFloats.txt"
read_file(filename)
print('Successfully completed placing values in array.')
main()
Seems straight-forward enough, but when I try execute, I get the following error:
Traceback (most recent call last):
File "sortFloat.py", line 14, in <module>
main()
File "sortFloat.py", line 11, in main
read_file(filename)
File "sortFloat.py", line 7, in read_file
array.append(line)
TypeError: descriptor 'append' requires a 'array.array' object but received a 'str'
I know Python views the contents of a file as a massive string and that I've created a float array, but that's not even the problem... it's wanting me to pass it an array.array object instead of the plain string. This problem persists if I convert it to a float.
How do I fix this? And before people suggest a list, yes, I do want the data in an array.