In [1]:
import csv

In [2]:
mesa = [
    {'first': 'joe', 'last': 'lutz', 'address': 'aqui'},
    {'first': 'mike', 'address': 'panera', 'last': 'duncan'},
    {'address': 'nashville', 'first': 'travis', 'last': 'cash'},
]

In [3]:
mesa


Out[3]:
[{'address': 'aqui', 'first': 'joe', 'last': 'lutz'},
 {'address': 'panera', 'first': 'mike', 'last': 'duncan'},
 {'address': 'nashville', 'first': 'travis', 'last': 'cash'}]

In [4]:
columns = ['last', 'first', 'address']

In [5]:
# excel_tab dialect was likely supported on creaky old version
# but required a hyphen instead of underscore.
with open('eggs.csv', 'wb') as csvfile:
    writer = csv.DictWriter(csvfile, columns, dialect='excel-tab')
    for row in mesa:
        writer.writerow(row)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-2fc79a20f139> in <module>()
      4     writer = csv.DictWriter(csvfile, columns, dialect='excel-tab')
      5     for row in mesa:
----> 6         writer.writerow(row)

/usr/lib/python3.5/csv.py in writerow(self, rowdict)
    151 
    152     def writerow(self, rowdict):
--> 153         return self.writer.writerow(self._dict_to_list(rowdict))
    154 
    155     def writerows(self, rowdicts):

TypeError: a bytes-like object is required, not 'str'

So do not write in binary mode.

That is a difference between the csv module of legacy Python and the csv module of modern Python.


In [6]:
with open('eggs.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, columns, dialect='excel-tab')
    for row in mesa:
        writer.writerow(row)

In [7]:
!ls -l eggs.csv


-rw-rw-r-- 1 doj doj 58 Feb 15 09:19 eggs.csv

In [8]:
!cat eggs.csv





In [9]:
print(repr(open('eggs.csv').read()))


'lutz\tjoe\taqui\nduncan\tmike\tpanera\ncash\ttravis\tnashville\n'

Would like to have something like following to output the results of a query. Catherine probably knows the canonical example for such for an Oracle database.


In [ ]:
with open('eggs.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, columns, dialect='excel-tab')
    query_results = do_query(FOO_QUERY_SQL)  # This is fakey stub.
    for row in query_results:
        writer.writerow(row)

In [ ]:
with open('eggs.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, columns, dialect='excel-tab')
    for row in do_query(FOO_QUERY_SQL):  # This is a fakey stub.
        writer.writerow(row)

In [ ]:
import psycopg2