63350

Save data to csv file using Python

Question:

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.

Answer1:

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 <a href="https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python" rel="nofollow">anwser</a>:

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.

Recommend

  • Insert data in multiple table with single button click
  • Determine if DateTime is in a given Date Range
  • Highcharts single row stacked horizontal bar: labels overlap — bar segments too small to read “dataL
  • Xml query resulting in error in sql server
  • vb.net bindingSource and bindingNavigation programatically
  • HTML XPath: Selectively avoiding tags when extracting text
  • How to remove comma or any characters from Python dataframe column name
  • SSH in Bash Script Messing Up File Read
  • Wrong labels when plotting a time series pandas dataframe with matplotlib
  • Python ImageIO Gif Set Delay Between Frames
  • Enabling DTD support in Sql Server
  • Center align outputs in ipython notebook
  • During installation of Django, why do I keep getting ImportError: No module named django?
  • where do I find the xml.dom python package for the python-2.6.0-8.9.28 and I have a suse/x86_64 vers
  • Python pickle not one-to-one: different pickles give same object
  • python script hangs on input method when running spark
  • How to generate and display a QR Code in ionic 2
  • pyodbc doesn't report sql server error
  • gspread or such: help me get cell coordinates (not value)
  • Textfile Structure (tables)
  • Setting up SourceTree to merge unity3d scenes with UnityYAMLMerge
  • Python urlparse: small issue
  • Email format validation in mvc3 view
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • How to add date and time under each post in guestbook in google app engine
  • Check if a string to interpolate provides expected placeholders
  • Matplotlib draw Spline from multiple points
  • Why winpcap requires both .lib and .dll to run?
  • align graphs with different xlab
  • Return words with double consecutive letters
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • Unanticipated behavior
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • Python: how to group similar lists together in a list of lists?
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • coudnt use logback because of log4j
  • Can't mass-assign protected attributes when import data from csv file
  • Busy indicator not showing up in wpf window [duplicate]
  • Unable to use reactive element in my shiny app