0

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.

abn
  • 1,353
  • 4
  • 28
  • 58

1 Answers1

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.

Community
  • 1
  • 1
Marcin
  • 215,873
  • 14
  • 235
  • 294