简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM