简体   繁体   English

将浮点数组写入CSV文件

[英]Write a float array to a CSV file

I have a float array (created by: array('f') ) and I want to write its contents as a 1-column CSV file, that is, each element of the array will take one line of the resulting file. 我有一个float数组(创建者: array('f') ),我想将其内容写为1列CSV文件,也就是说,数组的每个元素都将占用结果文件的一行。

from array import array

my_array = array('f')
with open(filename, 'w') as output:
    my_array = populate_method()
    writer = csv.writer(output)
    print(my_array)  # verifying that the data exist
    writer.writerows(my_array.tolist())

I get this error at the latest line: _csv.Error: sequence expected . 我在最新的行上收到此错误: _csv.Error: sequence expected
What is wrong? 怎么了? Isn't the list a sequence? 列表不是序列吗?

why ... you can just write it 为什么...你可以写它

with open("outfile","wb") as f:
     f.write("\n".join(str(x) for x in my_list))

the problem with your original code is that writerows expects a 2d list and you are just giving it a one dimensional list, therfor alternatively you can convert your 1d list into a 1column 2d list with 原始代码的问题是writerows需要一个2d列表,而您只是给它一个一维列表,因此也可以将您的1d列表转换为1column 2d列表,

my_list_i_can_use_with_writerows = zip(*[myList])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM