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,
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.
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.
To copy a table or query to a csv file, use either the \copy command or the COPY command.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With