Home > Net >  How to add a list with a list and integers into a csv?
How to add a list with a list and integers into a csv?

Time:11-10

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?

CodePudding user response:

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

CodePudding user response:

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)
  • Related