Save data to csv file using Python

坚强是说给别人听的谎言 提交于 2019-12-13 02:59:53

问题


My data, that I've extracted from a webpage looks like below after using print statement.

[[u'Neoplasms', u'Medical Subject Headings', u'direct', u'cancer', u'Neoplasms', u'Medical Subject Headings', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus', u'direct', u'cancer', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus']]

I'd like to write it to a csv file like this, with each row containing six elements.

Neoplasms, Medical Subject Headings, direct, cancer, Neoplasms, Medical Subject Headings
Malignant Neoplasm, National Cancer Institute Thesaurus, direct, cancer, Malignant Neoplasm, National Cancer Institute Thesaurus

Please suggest me how I can go about doing that.


回答1:


In python 2.7 you can do as follows:

import csv

data = [[u'Neoplasms', u'Medical Subject Headings', u'direct', u'cancer', u'Neoplasms', u'Medical Subject Headings', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus', u'direct', u'cancer', u'Malignant Neoplasm', u'National Cancer Institute Thesaurus']]


with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerows(data)

Update:

To get six element chunks of the input data: one can use the following function from this anwser:

def chunks(l, n):
    """ Yield successive n-sized chunks from l.  """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

Then to write the chunks, you can use:

with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile)

    for a_chunk in chunks(data[0], 6):     
        csvwriter.writerow(a_chunk)

Please note, that it is not clear if the input data is a list of many lists, or only one list embedded in other. I assumed the later.



来源:https://stackoverflow.com/questions/26878832/save-data-to-csv-file-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!