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

前端 未结 8 2019
南方客
南方客 2020-12-05 00:05

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...

8条回答
  •  时光取名叫无心
    2020-12-05 01:08

    import csv
    import sqlite3
    
    from glob import glob; from os.path import expanduser
    conn = 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.

提交回复
热议问题