Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export sqlite to CSV in Python without being formatted as a list?

Tags:

Here is what I currently have:

conn = sqlite3.connect(dbfile) conn.text_factory = str ## my current (failed) attempt to resolve this cur = conn.cursor() data = cur.execute("SELECT * FROM mytable")  f = open('output.csv', 'w') print >> f, "Column1, Column2, Column3, Etc." for row in data:   print >> f, row f.close() 

It creates a CSV file with output that looks like this:

Column1, Column2, Column3, Etc. (1, u'2011-05-05 23:42:29',298776684,1448052234,463564768,-1130996322, None, u'2011-05-06 04:44:41') 

I don't want the rows to be in parentheses nor have quotes nor the 'u' before strings. How do I get it to write the rows to csv without all of this? Thanks,

like image 569
Dan Avatar asked May 09 '12 19:05

Dan


People also ask

How do I export a SQLite database from CSV to Python?

The Best way to convert any Sqlite database to CSV file in python. The best approach to convert any SQLite database to a CSV file is to use pandas. we can first convert an SQLite database data to a dataframe and then convert this dataframe into a CSV file using the pandas module.

How fetch all data from SQLite database in Python?

SQLite Python: Querying Data First, establish a connection to the SQLite database by creating a Connection object. Next, create a Cursor object using the cursor method of the Connection object. Then, execute a SELECT statement. After that, call the fetchall() method of the cursor object to fetch the data.

Which command is used to copy a data from SQLite table to CSV file?

To copy a table or query to a csv file, use either the \copy command or the COPY command.


1 Answers

What you're currently doing is printing out the python string representation of a tuple, i.e. the return value of str(row). That includes the quotes and 'u's and parentheses and so on.

Instead, you want the data formatted properly for a CSV file. Well, try the csv module. It knows how to format things for CSV files, unsurprisingly enough.

with open('output.csv', 'wb') as f:     writer = csv.writer(f)     writer.writerow(['Column 1', 'Column 2', ...])     writer.writerows(data) 
like image 125
Danica Avatar answered Sep 22 '22 04:09

Danica