dump csv from sqlalchemy

前端 未结 8 457
时光取名叫无心
时光取名叫无心 2020-12-02 17:48

For some reason, I want to dump a table from a database (sqlite3) in the form of a csv file. I\'m using a python script with elixir (based on sqlalchemy) to modify the datab

8条回答
  •  既然无缘
    2020-12-02 17:59

    There are numerous ways to achieve this, including a simple os.system() call to the sqlite3 utility if you have that installed, but here's roughly what I'd do from Python:

    import sqlite3
    import csv
    
    con = sqlite3.connect('mydatabase.db')
    outfile = open('mydump.csv', 'wb')
    outcsv = csv.writer(outfile)
    
    cursor = con.execute('select * from mytable')
    
    # dump column titles (optional)
    outcsv.writerow(x[0] for x in cursor.description)
    # dump rows
    outcsv.writerows(cursor.fetchall())
    
    outfile.close()
    

提交回复
热议问题