1

I want to write the results of a query to a CSV file. I tried the solution from this other SO question: dump csv from sqlalchemy, but got _csv.Error: sequence expected. Why am I getting this error? How do I correctly write my query results to CSV?

fh = open('data.csv', 'wb')
outcsv = csv.writer(fh)
result = Grant.query.filter(Grant.pi_name==(piname)).all()
for res in result:
    outcsv.writerows(res)
fh.close()
Community
  • 1
  • 1
jk0104
  • 151
  • 1
  • 2
  • 10

1 Answers1

2

In the code you tried outcsv.writerows expects a collection of tuples to write. The query you wrote queries a model, which returns instances of that model. Additionally, you're passing each row individually to writerows, but as the plural in the name suggests you should pass all the rows. Query the model's table instead, and pass the result to writerows directly.

entries = db.session.query(Grant.__table__).filter(Grant.pi_name == pi_name)

with open('entries.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(entries)
davidism
  • 121,510
  • 29
  • 395
  • 339