0

I am trying to put the following into a csv. Here is my code

import csv  

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

with open('test.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(data)

I am getting the following error:

_csv.Error: iterable expected, not int

When writing writer.writerow, then the code works but gives [1, 2, 3], 4 and 5 as the columns.

I want the columns to be 1, 2, 3, 4, 5

Any help on how I can do it?

  • 1
    Sure. Do not give it a list in the 1st index but flatten your list. Search SO for "How to flatten a list" - should provide several hits. then `writer.writerows([[1,2,3,4,5]])` (or `writer.writerow([1,2,3,4,5])`) – Patrick Artner Nov 09 '21 at 20:18
  • I tried using reduce and also using list comprehension but in both, it says it cannot concatenate int or int is not iterable –  Nov 09 '21 at 20:43
  • [flattening-mixed-lists-in-python-containing-iterables-and-noniterables](https://stackoverflow.com/questions/3172930/flattening-mixed-lists-in-python-containing-iterables-and-noniterables) – Patrick Artner Nov 09 '21 at 20:54

2 Answers2

0

writerow isn't equivalent to writerows

>>> some_data = [[1,2,3],[4,5,6],[7,8,9]]
>>> writer.writerows(some_data)
>
1,2,3
4,5,6
7,8,9

>>> write.writerow(some_data)
>"[1, 2, 3]","[4, 5, 6]","[7, 8, 9]"

Try:

import csv

headers = [1,2,3,4,5]
some_data = ['Foo','Bar','Baz','Qux','Zoo']
more_data = [['d1','d2','d3'],['d4','d5','d6']]

with open('test.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(headers)     # Takes an iterable of cells
    writer.writerow(some_data)
    writer.writerows(more_data)  # Takes an iterable of iterables

And you'll get:

1,2,3,4,5
Foo,Bar,Baz,Qux,Zoo
d1,d2,d3
d4,d5,d6
0
import csv  

data = [[1, 2, 3,4], 5,6]

print_data = []

with open('test.csv', 'w') as f:
    writer = csv.writer(f)
    # Following code flattens the list within a list,
    # uses temporary 'print_data' to store values for printing to csv 
    for counter in range(len(data)):  
        if isinstance(data[counter], list)==1 :
            print ('list found')
            for val in data[counter]:
                print_data.append(val)
        else:
             print_data.append(data[counter])

    writer.writerow(print_data)