dump csv from sqlalchemy

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

    I adapted the above examples to my sqlalchemy based code like this:

    import csv
    import sqlalchemy as sqAl
    
    metadata = sqAl.MetaData()
    engine = sqAl.create_engine('sqlite:///%s' % 'data.db')
    metadata.bind = engine
    
    mytable = sqAl.Table('sometable', metadata, autoload=True)
    db_connection = engine.connect()
    
    select = sqAl.sql.select([mytable])
    result = db_connection.execute(select)
    
    fh = open('data.csv', 'wb')
    outcsv = csv.writer(fh)
    
    outcsv.writerow(result.keys())
    outcsv.writerows(result)
    
    fh.close
    

    This works for me with sqlalchemy 0.7.9. I suppose that this would work with all sqlalchemy table and result objects.

提交回复
热议问题