0

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.

4 Answers 4

2

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

That would try and put a str object in an array that expects a float. How would that work?
@EricUrban Correct. I missed that one. Fixed it.
1
import array
a = array.array('f')
with open('filename', 'r') as f:
    a.fromlist(map(float, f.read().strip().split()))
print a

1 Comment

Good answer, but f.read() requires the whole file to be read into memory, then split into an array of strings. For small files this works. It is better to iterate across the file if it is large.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.