Skip to content Skip to sidebar Skip to footer

Save Data To Csv File Using Python

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'Medica

Solution 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']]


withopen('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:

defchunks(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:

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

    for a_chunk inchunks(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.

Post a Comment for "Save Data To Csv File Using Python"