2

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?

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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()

1 Comment

This won't work correctly, if one of the values contain \n or ,.
0

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)

Comments

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.