Reputation: 1297
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.
Upvotes: 0
Views: 7085
Reputation: 20361
Ok... so what you need to do is:
array1 = array('f') # Assign that object to a variable.
And later:
array1.append(line)
The error you are getting is because you don't actually create a variable that can be accessed. Therefore when we call the append method we don't actually specify the array that we want to append to, only the string we want to add.
Upvotes: 1
Reputation: 5914
import array
a = array.array('f')
with open('filename', 'r') as f:
a.fromlist(map(float, f.read().strip().split()))
print a
Upvotes: 1
Reputation: 3820
The call to array('f')
creates an instance which you need to store a reference to. Also, strip each line of whitespace, and interpret it as a floating point number. Close the file when you are done.
from array import array
def read_file(infilename):
infile = open(infilename, 'r')
arr = array('f') #Store the reference to the array
for line in infile:
arr.append(float(line.strip())) #Remove whitespace, cast to float
infile.close()
return arr
def main():
filename = "randFloats.txt"
arr = read_file(filename)
print('Successfully completed placing %d values in array.' % len(arr))
main()
Upvotes: 2
Reputation: 6144
You need to instantiate the array first into a variable, say arr
and then use it to append the values,
def read_file(infilename):
infile = open(infilename, 'r')
arr = array('f')
for line in infile:
arr.append(float(line)) # <-- use the built-in float to convert the str to float
Also, you might need to return the variable arr
after appending all the values to it,
def read_file(infilename):
...
return arr
Upvotes: 1