Search code examples
pythonarrayslistcsvexport-to-csv

Best way to save a CSV file of a 2 dimensional array or list in Python?


In Python I am putting together a 2D array/list that could be represented like this:

a b 
c d

And I want to save it in a CSV file and have the CSV file look like this:

a, b
c, d

This is the code I am using. What am I doing wrong?

import csv

testarray = [["a", "b"], ["c", "d"]]

with open('test.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',',  quotechar='"',
                                 quoting=csv.QUOTE_MINIMAL)
    employee_writer.writerow(testarray)

# Outputs 
# "['a', 'b']","['c', 'd']"

How can I change my code to output:

Preferably:

a, b 
c, d

Or:

'a', 'b' 
'c', 'd'

In the text file?


Solution

  • If testarray contains multiple rows. Use writerows instead of writerow

    import csv
    
    testarray = [["a", "b"], ["c", "d"]]
    
    with open('test.csv', mode='w') as employee_file:
        employee_writer = csv.writer(employee_file, delimiter=',',  quotechar='"',
                                     quoting=csv.QUOTE_MINIMAL)
        employee_writer.writerows(testarray)