251

I am trying to create a .csv file with the values from a Python list. When I print the values in the list they are all unicode (?), i.e. they look something like this

[u'value 1', u'value 2', ...]

If I iterate through the values in the list i.e. for v in mylist: print v they appear to be plain text.

And I can put a , between each with print ','.join(mylist)

And I can output to a file, i.e.

myfile = open(...)
print >>myfile, ','.join(mylist)

But I want to output to a CSV and have delimiters around the values in the list e.g.

"value 1", "value 2", ... 

I can't find an easy way to include the delimiters in the formatting, e.g. I have tried through the join statement. How can I do this?

Austin Cummings
  • 770
  • 1
  • 8
  • 15
Fortilan
  • 2,645
  • 2
  • 17
  • 10
  • Thanks everyone, I have combined the ideas from a few answers to solve my question :) I now use the csv module to write the [...] data straight into a file import csv data = [...] myfile = open(..., 'wb') out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL) out.writerow(data) works well, I construct my data[] by grabbing some data out a spreadsheet using xlrd and the csv module writes it out to a file with the right delimiters all good :) ty all again – Fortilan Jan 21 '10 at 04:34
  • 1
    A more recent approach could be to use [pandas](http://pandas.pydata.org/pandas-docs/stable/io.html#io-store-in-csv) – Richard Apr 13 '16 at 06:13
  • Python 3.4 users, this worked best for me: http://stackoverflow.com/questions/25022677/python-3-4-writing-a-list-to-a-csv?newreg=95656f0c688e4ee6ac073dbca96177c1 – Leigh Apr 26 '16 at 21:53
  • 1
    See also: [How do I read and write CSV files with Python?](http://stackoverflow.com/q/41585078/562769) – Martin Thoma Feb 03 '17 at 11:48

13 Answers13

313
import csv

with open(..., 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(mylist)

Edit: this only works with python 2.x.

To make it work with python 3.x replace wb with w (see this SO answer)

with open(..., 'w', newline='') as myfile:
     wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
     wr.writerow(mylist)
Giampaolo Ferradini
  • 529
  • 1
  • 6
  • 17
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 11
    Do note that the `csv` module in 2.x does not deal properly with unicodes; see the module documentation for examples on how to deal with this. http://docs.python.org/library/csv.html – Ignacio Vazquez-Abrams Jan 18 '10 at 07:39
  • 19
    you can also use wr.writerows(list) – tovmeod Dec 25 '11 at 22:29
  • What is the difference between writerow and writerows? – tumultous_rooster Jun 09 '14 at 05:52
  • 5
    Writerows seems to break up each element in the list into columns if each element is a list as well. This is pretty handy for outputting tables. – whatnick Oct 07 '14 at 05:22
  • 6
    That does not work with python 3.4. I am getting `TypeError: 'str' does not support the buffer interface`. – botchniaque Sep 15 '15 at 13:17
  • 1
    For Python 2, use `'w'` as here: https://stackoverflow.com/questions/34283178/typeerror-a-bytes-like-object-is-required-not-str-in-python-and-csv – banan3'14 Jan 03 '19 at 19:39
  • @botchniaque would suggest you use 'wt' if you are trying to write text to a file – don_Gunner94 Mar 04 '20 at 11:40
  • This seems to write list into columns of csv. Is there a way to write values into rows? – Xin Niu Apr 11 '22 at 18:50
  • @Alex Martelli: I have a list where each element of the list is a string. I need each element of the list to be written in each row. So, for instance: "hello1" to ```row1```, "hello2" to ```row2```... What really happens with the above code is that it breaks, for example, "hello1" into "h" "e" "l" "l" "o" "1" and it rights them in ```row1``` ***but*** each character in different column (of ```row1```)... How can I fix that? – just_learning Aug 23 '22 at 16:59
125

Here is a secure version of Alex Martelli's:

import csv

with open('filename', 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    wr.writerow(mylist)
Cristian Garcia
  • 9,630
  • 6
  • 54
  • 75
  • 5
    plus 1 for using `with`, making sure the file is closed when done – BoltzmannBrain May 15 '15 at 20:20
  • If I am using this inside a for loop, should the entire with block be nested under the for loop? Or would it be more efficient to only have `wr.writerow(my_list)` inside the loop? – crypdick Jun 07 '17 at 23:05
  • 1
    @crypdick you should definitely not put the entire block into the loop. Open the file, then write each row in a loop. There's no need to open the file n times to write n rows. – Greg Kaleka Nov 14 '17 at 00:17
  • 1
    If you are writing string objects to a file, would suggest using 'wt' while opening file to avoid TypeError: a bytes-like object is required, not 'str'. – don_Gunner94 Mar 04 '20 at 11:39
  • To avoid using `with`, instead use `f = open("myfile.csv","w")` , `out = csv.writer(f, delimiter=',',quoting=csv.QUOTE_ALL)`, `out.writerow([11,22,338])` , `f.close()` – Pe Dro May 14 '22 at 06:01
70

For another approach, you can use DataFrame in pandas: And it can easily dump the data to csv just like the code below:

import pandas
df = pandas.DataFrame(data={"col1": list_1, "col2": list_2})
df.to_csv("./file.csv", sep=',',index=False)
Qy Zuo
  • 2,622
  • 24
  • 21
  • 3
    Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its educational value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Jul 05 '17 at 09:10
  • 5
    Also for this to work the lists need to have the same length, otherwise you'll get a ValueError (pandas v 0.22.0) – cheevahagadog May 03 '18 at 21:37
40

The best option I've found was using the savetxt from the numpy module:

import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)

In case you have multiple lists that need to be stacked

np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)
tokenizer_fsj
  • 1,130
  • 13
  • 18
12

Use python's csv module for reading and writing comma or tab-delimited files. The csv module is preferred because it gives you good control over quoting.

For example, here is the worked example for you:

import csv
data = ["value %d" % i for i in range(1,4)]

out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)

Produces:

"value 1","value 2","value 3"
vy32
  • 28,461
  • 37
  • 122
  • 246
  • 5
    Produces an empty file for me – caspii Oct 08 '17 at 13:38
  • First run is empty and you also cannot delete it then, because it is then opened in python. Second run (or more precise: `out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL))` fills the data, no matter if you put `open("myfile.csv","w")` or a new file `open("myfile2.csv","w")`. Seems as if the out object cannot deal with the file object built on the run, but stores the output process as a todo. In otherwords: the out object stores the file object in the first run but is only writing when the file object already exists! See the right solution below @Saurabh Adhikary – questionto42 May 21 '20 at 10:12
9

Jupyter notebook

Let's say that your list name is A

Then you can code the following and you will have it as a csv file (columns only!)

R="\n".join(A)
f = open('Columns.csv','w')
f.write(R)
f.close()
Syed Adnan Haider
  • 74
  • 1
  • 2
  • 11
rsc05
  • 3,626
  • 2
  • 36
  • 57
8

You could use the string.join method in this case.

Split over a few of lines for clarity - here's an interactive session

>>> a = ['a','b','c']
>>> first = '", "'.join(a)
>>> second = '"%s"' % first
>>> print second
"a", "b", "c"

Or as a single line

>>> print ('"%s"') % '", "'.join(a)
"a", "b", "c"

However, you may have a problem is your strings have got embedded quotes. If this is the case you'll need to decide how to escape them.

The CSV module can take care of all of this for you, allowing you to choose between various quoting options (all fields, only fields with quotes and seperators, only non numeric fields, etc) and how to esacpe control charecters (double quotes, or escaped strings). If your values are simple, string.join will probably be OK but if you're having to manage lots of edge cases, use the module available.

Robert Christie
  • 20,177
  • 8
  • 42
  • 37
8

This solutions sounds crazy, but works smooth as honey

import csv

with open('filename', 'wb') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL,delimiter='\n')
    wr.writerow(mylist)

The file is being written by csvwriter hence csv properties are maintained i.e. comma separated. The delimiter helps in the main part by moving list items to next line, each time.

Storm
  • 355
  • 5
  • 14
8

Here is working copy-paste example for Python 3.x with options to define your own delimiter and quote char.

import csv

mylist = ['value 1', 'value 2', 'value 3']

with open('employee_file.csv', mode='w') as employee_file:
    employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
    employee_writer.writerow(mylist)

This will generate employee_file.csv that looks like this:

"value 1","value 2","value 3"

NOTE:

If quoting is set to csv.QUOTE_MINIMAL, then .writerow() will quote fields only if they contain the delimiter or the quotechar. This is the default case.

If quoting is set to csv.QUOTE_ALL, then .writerow() will quote all fields.

If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote all fields containing text data and convert all numeric fields to the float data type.

If quoting is set to csv.QUOTE_NONE, then .writerow() will escape delimiters instead of quoting them. In this case, you also must provide a value for the escapechar optional parameter.

Hrvoje
  • 13,566
  • 7
  • 90
  • 104
4

To create and write into a csv file

The below example demonstrate creating and writing a csv file. to make a dynamic file writer we need to import a package import csv, then need to create an instance of the file with file reference Ex:- with open("D:\sample.csv","w",newline="") as file_writer

here if the file does not exist with the mentioned file directory then python will create a same file in the specified directory, and "w" represents write, if you want to read a file then replace "w" with "r" or to append to existing file then "a". newline="" specifies that it removes an extra empty row for every time you create row so to eliminate empty row we use newline="", create some field names(column names) using list like fields=["Names","Age","Class"], then apply to writer instance like writer=csv.DictWriter(file_writer,fieldnames=fields) here using Dictionary writer and assigning column names, to write column names to csv we use writer.writeheader() and to write values we use writer.writerow({"Names":"John","Age":20,"Class":"12A"}) ,while writing file values must be passed using dictionary method , here the key is column name and value is your respective key value

import csv 

with open("D:\\sample.csv","w",newline="") as file_writer:

   fields=["Names","Age","Class"]

   writer=csv.DictWriter(file_writer,fieldnames=fields)

   writer.writeheader()

   writer.writerow({"Names":"John","Age":21,"Class":"12A"})
prosoitos
  • 6,679
  • 5
  • 27
  • 41
2

For those looking for less complicated solution. I actually find this one more simplisitic solution that will do similar job:

import pandas as pd
a = ['a','b','c'] 
df = pd.DataFrame({'a': a})
df= df.set_index('a').T
df.to_csv('list_a.csv', index=False)

Hope this helps as well.

smerllo
  • 3,117
  • 1
  • 22
  • 37
1

you should use the CSV module for sure , but the chances are , you need to write unicode . For those Who need to write unicode , this is the class from example page , that you can use as a util module:

import csv, codecs, cStringIO

class UTF8Recoder:
    """
    Iterator that reads an encoded stream and reencodes the input to UTF-8
    """
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)

def __iter__(self):
    return self

def next(self):
    return self.reader.next().encode("utf-8")

class UnicodeReader:
    """
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.
    """

def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    f = UTF8Recoder(f, encoding)
    self.reader = csv.reader(f, dialect=dialect, **kwds)

def next(self):
    row = self.reader.next()
    return [unicode(s, "utf-8") for s in row]

def __iter__(self):
    return self

class UnicodeWriter:
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.
"""

def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
    # Redirect output to a queue
    self.queue = cStringIO.StringIO()
    self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
    self.stream = f
    self.encoder = codecs.getincrementalencoder(encoding)()

def writerow(self, row):
    self.writer.writerow([s.encode("utf-8") for s in row])
    # Fetch UTF-8 output from the queue ...
    data = self.queue.getvalue()
    data = data.decode("utf-8")
    # ... and reencode it into the target encoding
    data = self.encoder.encode(data)
    # write to the target stream
    self.stream.write(data)
    # empty queue
    self.queue.truncate(0)

def writerows(self, rows):
    for row in rows:
        self.writerow(row)
kommradHomer
  • 4,127
  • 5
  • 51
  • 68
1

Here is another solution that does not require the csv module.

print ', '.join(['"'+i+'"' for i in myList])

Example :

>>> myList = [u'value 1', u'value 2', u'value 3']
>>> print ', '.join(['"'+i+'"' for i in myList])
"value 1", "value 2", "value 3"

However, if the initial list contains some ", they will not be escaped. If it is required, it is possible to call a function to escape it like that :

print ', '.join(['"'+myFunction(i)+'"' for i in myList])
Richard
  • 992
  • 1
  • 11
  • 27