SVM
SVM

Reputation: 11

Python write to csv in rows

Probably basic Python, but I can't get my head around it.

I have some results from a function which print as [{1,2,3},{4,5,6),{7,8,9}]. I want to write this to a csv like this:

A      B     C
1      2     3
4      5     6
7      8     9

With this code (note the writerow.):

filename = 'test.csv'

sr = []
for row in result:
    sr.append(row)

with open(filename, "wb") as f:
    writer = csv.writer(f, delimiter=';')
    writer.writerow(sr)

I get:

A        B        C
{1,2,3}  {4,5,6}  {7,8,9}

When I use writer.writerows(sr) I get _csv.Error: sequence expected. Which makes perfect sense because my initial result is just one row.

How to transform the data in such a way that I can get it to a csv like I want?

Upvotes: 0

Views: 77

Answers (2)

martineau
martineau

Reputation: 123393

To get the format the way you want would require something along these lines:

import csv

result = [{1, 2, 3}, {4, 5, 6}, {8, 9, 7}]
filename = 'testabc.csv'
header = 'A', 'B', 'C'

with open(filename, "wb") as f:
    writer = csv.writer(f, delimiter=';')
    writer.writerows(header)
    for row in result:
        writer.writerow(list(row))

A potential problem is that sets don't preserve order, so the items may end up in random order with each row (unless you manually sorted them).

Upvotes: 0

Ayoub
Ayoub

Reputation: 1435

If your result looks like this:

result = [{1, 2, 3}, {4, 5, 6}, {8, 9, 7}]

You could write it directly using writerows:

import csv

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

writerows takes an iterable of iterable which is a set in your case but if you use writerow instead it'll write your result in a single line which give a set per column

Upvotes: 1

Related Questions