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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's part of it, but OP also wants the items split up into rows of 6 items each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.