Write a list into csv in python

时间:2017-08-05 11:22:38

标签: python

I want to write a list into a csv file in python. This is a subset of my input list.

rows= ([u'Feng Ming', u'Cao', u'China Samsung Telecom', u'Beijing', u'', u'CHINA'], 
    [u'Naftali', u'Chayat', u'Alvarion Ltd.', u'Tel Aviv', u'', u'ISRAEL'],
    [u'R\xe9mi', u'Chayer', u'Harris Corporation', u'Dollard-Des-Ormeaux', u'PQ', u'CANADA'])

However, when I am using the code

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

Its showing error because of the character "R\xe9mi". Any lead to solve this problem will be appreciated. Thanks

2 个答案:

答案 0 :(得分:1)

You have to add import unicodecsv as csv to do this task.

import unicodecsv as csv
rows= [u'Feng Ming', u'Cao', u'China Samsung Telecom', u'Beijing', u'', u'CHINA'], [u'Naftali', u'Chayat', u'Alvarion Ltd.', u'Tel Aviv', u'', u'ISRAEL'], [u'R\xe9mi', u'Chayer', u'Harris Corporation', u'Dollard-Des-Ormeaux', u'PQ', u'CANADA']

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(rows)

output.csv :

Feng Ming,Cao,China Samsung Telecom,Beijing,,CHINA
Naftali,Chayat,Alvarion Ltd.,Tel Aviv,,ISRAEL
Rémi,Chayer,Harris Corporation,Dollard-Des-Ormeaux,PQ,CANADA

答案 1 :(得分:0)

Just use unicodecsv

pip install unicodecsv

import unicodecsv as csv
# Your code