How do I create a CSV file from database in Python? How do I create a CSV file from database in Python? mysql mysql

How do I create a CSV file from database in Python?


import csvimport sqlite3from glob import glob; from os.path import expanduserconn = sqlite3.connect( # open "places.sqlite" from one of the Firefox profiles    glob(expanduser('~/.mozilla/firefox/*/places.sqlite'))[0])cursor = conn.cursor()cursor.execute("select * from moz_places;")with open("out.csv", "w", newline='') as csv_file:  # Python 3 version    #with open("out.csv", "wb") as csv_file:              # Python 2 version    csv_writer = csv.writer(csv_file)    csv_writer.writerow([i[0] for i in cursor.description]) # write headers    csv_writer.writerows(cursor)

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


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

import csvwriter = 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.


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.