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.
PEP 249 (DB API 2.0) has more information about
cursor.description
.unless i'm missing something, you just want to do something like so...
logic to write lines to file (you may need to organize values and add comms or pipes etc...)
You seem to be familiar with excel and want to stay close to it. Might I suggest trying PyExcelerator?
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 :
Which will create a csv file with tab separator.
Using the csv module is very straight forward and made for this task.
Creates exactly the format you're expecting.
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. It gives you useful information about each column in a table, including the name of the column.Example:
Other problems with the now-deleted "parse the create table SQL" answer:
Stuffs up with e.g.
create table test (id1 text, id2 int, msg text, primary key(id1, id2))
... needs to ignore not onlyCONSTRAINT
, but also keywordsPRIMARY
,UNIQUE
,CHECK
andFOREIGN
(see thecreate table
docs).Needs to specify
re.DOTALL
in case there are newlines in the SQL.In
line.split()[0].strip()
thestrip
is redundant.