2

I have been trying to put list in to csv file but it's not taking the whole word as input but as a letter and inserting every letter in separate cell

import csv

data = {}

with open('test.csv','w',newline='') as fp:

    a = csv.writer(fp,delimiter=',')
    data = ['sales','tax']
    a.writerows(data)

The output is:

s       a    l  e   s
t   a   x       

with each letter in separate cell

I need output like:

Sales
Tax
Underoos
  • 3,105
  • 3
  • 22
  • 47
  • Possible duplicate of [Writing a Python list of lists to a csv file](https://stackoverflow.com/questions/14037540/writing-a-python-list-of-lists-to-a-csv-file) – Amit Gupta Apr 12 '19 at 07:57
  • Do you want `sales` and `tax` on a line each or as columns on the same line? – Holloway Apr 12 '19 at 08:05

2 Answers2

5

.writerows() (plural) expects a list of lists (or more accurately, an iterable of iterables) representing multiple rows. Use .writerow() (singular) to pass a single list representing one row.

To explain your current output...since a string is iterable, a list of strings looks like an iterable of iterables, but each column ends up being a single letter when used with .writerows().

Mark Tolonen
  • 132,868
  • 21
  • 152
  • 208
3
data = ['sales','tax']
a.writerows(data)

Is treating data as a list of rows, not as a single row. Try

data = [['sales', 'tax']]
a.writerows(data)

Where data is a list containing a single list (row).

Or

data = ['sales', 'tax']
a.writerow(data) # note row not rows

to write a single row.

Holloway
  • 4,301
  • 1
  • 25
  • 30