2

I am trying to save arrays into a csv file using python.

I have an array of arrays:

myarr = [[10.3,11.2,10.7],[13.4,12.6,12.7],[12.56,14.21,11.33]]

I would like to save it into a csv file into the following format:

    A      B      C
1  10.3   11.2   10.7
2  13.4   12.6   12.7
3  12.56  12.41  11.33

I need it to save without deleting previous rows, so if I go back into the same file to try and save more arrays, it shouldn't delete the old rows, it should start at the next available row.

Thank you for your help.

3
  • 6
    It would help if you could add some code you tried, some output you got/an error you got, how you want to name the rows and columns, and what type of values you're expecting. Commented Feb 20, 2014 at 6:16
  • 2
    Also, csv is short for comma separated values. Do you want commas, tabs or spaces as separators? Commented Feb 20, 2014 at 6:24
  • @SteinarLima commas. Code provided by Algiriyage is perfect except it rewrites instead of continues at new blank rows. Commented Feb 20, 2014 at 6:38

1 Answer 1

4

I have no idea of what these column headers are. Please explain it more. You can use following code to write the array in to a csv file row by row.

import csv
myarr = [[10.3,11.2,10.7],[13.4,12.6,12.7],[12.56,14.21,11.33]]
with open("myarray.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(myarr)
Sign up to request clarification or add additional context in comments.

5 Comments

what you have is perfect, but when I try to write more arrays afterwards, it rewrites. It does not start at the next blank row. The column headers just show the format I was looking for when it is written to excel
Just change the mode flag from 'wb' to 'a'
thanks and use lineterminator = '\n' when writing so it doesn't skip rows
@user1681664 : Sorry I didn't see your requirement. Yes you have to change 'wb' in to 'a' as Steinar has said. :)
Why are you using binary mode for csv file that is supposed to be textual?

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.