rmore911
rmore911

Reputation: 215

How to fix "Error: iterable expected, not int" when writing to a CSV file?

Why is my CSV write function not working? This seems to be a very simple code but the CSV writerow is asking for an iterable. I just need to write the 1,2,3 in a column.

import csv

data = [1,2,3]

output = 'output.csv'

with open(output,'w') as f:
    writer = csv.writer(f)
    for item in data:
        writer.writerow(item)

Upvotes: 0

Views: 8639

Answers (2)

Sohaib Anwaar
Sohaib Anwaar

Reputation: 1547

We need to provide a list to the CSV writer writerow function, in which there are values for 1 complete row.

e.g

import csv

data = [1,2,3]

output = 'output.csv'

with open(output,'w') as f:
    writer = csv.writer(f)
    writer.writerow(data) # as data includes only 1 row. For multiple rows write every row with a loop

Upvotes: 2

Joshua Lowry
Joshua Lowry

Reputation: 1105

You are passing an integer but a list is expected.

import csv

data = [[1],[2],[3]]

output = 'output.csv'

with open(output,'w') as f:
    writer = csv.writer(f)
    for item in data:
        writer.writerow(item)

Upvotes: 2

Related Questions