dump csv from sqlalchemy

前端 未结 8 453
时光取名叫无心
时光取名叫无心 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:57

    Modifying Peter Hansen's answer here a bit, to use SQLAlchemy instead of raw db access

    import csv
    outfile = open('mydump.csv', 'wb')
    outcsv = csv.writer(outfile)
    records = session.query(MyModel).all()
    [outcsv.writerow([getattr(curr, column.name) for column in MyTable.__mapper__.columns]) for curr in records]
    # or maybe use outcsv.writerows(records)
    
    outfile.close()
    

提交回复
热议问题