views:

416

answers:

6

I have a Sqlite 3 and/or MySQL table named "clients"..

Using python 2.6, How do I create a csv file named Clients100914.csv with headers? excel dialect...

The Sql execute: select * only gives table data, but I would like complete table with headers.

How do I create a record set to get table headers. The table headers should come directly from sql not written in python.

w = csv.writer(open(Fn,'wb'),dialect='excel')
#w.writelines("header_row")
#Fetch into sqld
w.writerows(sqld)

This code leaves me with file open and no headers. Also cant get figure out how to use file as log.

+4  A: 

You can easily create it manually, writing a file with a chosen separator. You can also use csv module.

If it's from database you can alo just use a query from your sqlite client :

sqlite <db params> < queryfile.sql > output.csv

Which will create a csv file with tab separator.

Guillaume Lebourgeois
Of course, the command `.separator ,` can be used in the commands to sqlite to make the csv file use comma separators.
Muhammad Alkarouri
Does it escape separators in data?
Alex B
A: 

unless i'm missing something, you just want to do something like so...

f = open("somefile.csv")
f.writelines("header_row")

logic to write lines to file (you may need to organize values and add comms or pipes etc...)

f.close()
jonny
though Guillaume's answer is more direct.
jonny
i need to pyodbc module, so i can use mysql later.
+7  A: 

Using the csv module is very straight forward and made for this task.

import csv
writer = csv.writer(open("out.csv", 'w'))
writer.writerow(['name', 'address', 'phone', 'etc'])
writer.writerow(['bob', '2 main st', '703', 'yada'])
writer.writerow(['mary', '3 main st', '704', 'yada'])

Creates exactly the format you're expecting.

Stephen Johnson
thanks, do i need to define each row. I thought i would need to create file with date, create headers row, select *, then insert Select * into csv.
Its does not write the headers of the table programatically.
+2  A: 

How to extract the column headings from an existing table:

You don't need to parse an SQL "create table" statement. This is fortunate, as the "create table" syntax is neither nice nor clean, it is warthog-ugly.

You can use the table_info pragma, described here. It gives you useful information about each column in a table, including the name of the column.

Example:

>>> #coding: ascii
... import sqlite3
>>>
>>> def get_col_names(cursor, table_name):
...     results = cursor.execute("PRAGMA table_info(%s);" % table_name)
...     return [row[1] for row in results]
...
>>> def wrong_way(cur, table):
...     import re
...     cur.execute("SELECT sql FROM sqlite_master WHERE name=?;", (table, ))
...     sql = cur.fetchone()[0]
...     column_defs = re.findall("[(](.*)[)]", sql)[0]
...     first_words = (line.split()[0].strip() for line in column_defs.split(','))
...     columns = [word for word in first_words if word.upper() != "CONSTRAINT"]
...     return columns
...
>>> conn = sqlite3.connect(":memory:")
>>> curs = conn.cursor()
>>> _ignored = curs.execute(
...     "create table foo (id integer, name text, [haha gotcha] text);"
...     )
>>> print get_col_names(curs, "foo")
[u'id', u'name', u'haha gotcha']
>>> print wrong_way(curs, "foo")
[u'id', u'name', u'[haha'] <<<<<===== WHOOPS!
>>>

Other problems with the now-deleted "parse the create table SQL" answer:

(a) Stuffs up with e.g. create table test (id1 text, id2 int, msg text, primary key(id1, id2)) ... needs to ignore not only CONSTRAINT but also keywords PRIMARY, UNIQUE, CHECK and FOREIGN (see create table docs)

(b) Needs to specify re.DOTALL in case there are newlines in the SQL.

(c) In line.split()[0].strip() the strip is redundant

John Machin
thanks, john.... in code below I had to add only two lines to existing code... Go Python!
+1  A: 
import csv
import sqlite3

conn = sqlite3.connect("Firefox/.../permissions.sqlite")
cursor = conn.cursor()
cursor.execute("select * from moz_hosts;")

csv_writer = csv.writer(open("out.csv", "wt"))
csv_writer.writerow([i[0] for i in cursor.description]) # write headers
csv_writer.writerows(cursor)
del csv_writer # this will close the CSV file

PEP 249 (DB API 2.0) has more information about (cursor).description.

Cristian Ciupitu
Ok, code looks much easier to understand and maintain, it same for MySql and Sybase, if chg connection string?
for row in cursor: csv_writer.writerow(row)>csv_writer.writerows(row)
@user428862: the code should also work with MySQL or Sybase databases. I've updated the answer with your suggestion.
Cristian Ciupitu
A: 

You seem to be familiar with excel and want to stay close to it. Might I suggest trying PyExcelerator?

inspectorG4dget
Is that you, Clippy? ^_-
Mike DeSimone
-1 pyExcelerator is abandonware. Use xlwt (http://www.python-excel.org) instead. It's a fork of pyExcelerator with bug fixes and several enhancements. [Dis]claimer: I'm the maintainer.
John Machin
I know excel/VBA, But moving away from MSFT and Windows.