blackmamba
blackmamba

Reputation: 2002

Write a set to csv file in Python

This is my set:

set(['description', 'title'])

I need this to write to a csv file in 2 columns. My code:

cw = csv.writer(open("hello.csv",'w'))
cw.writerows(cols)

Throws an error:

cw.writerow(cols)
_csv.Error: sequence expected

Add list to csv file:

cw.writerow(list(cols))
for row in data:
    cw.writerow([str(row.get(k,'N/A')) for k in cols])

Found a way to rectify this: Open a file in wb mode rather than in w mode

Upvotes: 6

Views: 31389

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123710

Turn your set into a list first:

cw.writerow(list(cols))

Note that the order in which the columns are written will be arbitrary; sets, like dictionaries, have no fixed order.

Upvotes: 8

Related Questions