我正在尝试从文件中获取浮点数并将它们放在数组中。每个浮子都有自己的线。我对Python有点新手(不是我想要执行的概念),而且它并没有像我期望的那样工作。
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()
看起来很直接,但是当我尝试执行时,我收到以下错误:
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'
我知道Python将文件的内容视为一个庞大的字符串并且我创建了一个浮点数组,但这甚至都不是问题...它希望我将它传递给array.array
对象而不是普通的字符串。如果我将它转换为浮点数,这个问题仍然存在。
我该如何解决这个问题?在人们建议列表之前,是的,我确实想要数组中的数据。
答案 0 :(得分:2)
对array('f')
的调用会创建一个您需要存储引用的实例。另外,剥离每行空格,并将其解释为浮点数。完成后关闭文件。
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()
答案 1 :(得分:1)
您需要先将数组实例化为变量,比如arr
,然后使用它来附加值,
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
此外,您可能需要在将所有值附加到其后返回变量arr
,
def read_file(infilename):
...
return arr
答案 2 :(得分:1)
import array
a = array.array('f')
with open('filename', 'r') as f:
a.fromlist(map(float, f.read().strip().split()))
print a
答案 3 :(得分:1)
好的......所以你需要做的是:
array1 = array('f') # Assign that object to a variable.
后来:
array1.append(line)
您获得的错误是因为您实际上并未创建可以访问的变量。因此,当我们调用append方法时,我们实际上并没有指定要追加的数组,只有我们要添加的字符串。