0

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.

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.
What is wrong? Isn't the list a sequence?

1 Answer 1

0

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

my_list_i_can_use_with_writerows = zip(*[myList])
Sign up to request clarification or add additional context in comments.

1 Comment

Writing it directly was my first attempt, but didn't came up with the "\n".join syntax and so all the elements were in one line. Some follow-up questions: 1. Why does write_rows expect a 2D list? 2. Could you elaborate on the syntax of zip(*[myList]) ?

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.