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

Viewed 718

Hi 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 can you please tell me what I am 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?

Many thanks again for all your help!

3 Answers

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)

You can use nested for loops to drop all the data in your preferred format:

# Initialize the array
test = [['1', '2'], ['3', '4']]

# Format the array to a string
merged = ""
for group in test:
     merged += ", ".join(group) + "\n"

# Write string to file
with open("test.csv", "w") as file:
    file.write(merged)
    file.close()

You need to loop over the individual entry of your testarray or simply use writerows.

import csv

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

with open('test.csv', mode='w', newline='') as employee_file:
    employee_writer = csv.writer(employee_file)
    employee_writer.writerow(["header1", "header2"])
    employee_writer.writerows(testarray)
Related