简体   繁体   中英

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)

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)

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

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM