I'm writing to a csv file in batches, and as I currently have it only the last 'batch' is being recorded on the file, whether I open the file with 'w' or 'a' flags. Here are my two attempts:
with open('testdump.csv', 'w') as csvfile:
fieldnames = ['name', 'price']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for date in date_list:
date = date.strftime('%Y-%m-%d')
q1 = db.session.query(...query goes here that depends on date...)
rows = []
for row in q1:
rows.append(
{
'name': row.name,
'price': row.price,
}
)
for row in rows:
writer.writerow(dict(
(k, v.encode('utf-8') if type(v) is unicode else v) for k, v in row.iteritems()
))
which results in only the last batch being written and
csvfile = open('testdump.csv', 'w')
fieldnames = ['name', 'price']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
csvfile.close()
for date in date_list:
date = date.strftime('%Y-%m-%d')
q1 = db.session.query(...query goes here that depends on date...)
rows = []
for row in q1:
rows.append(
{
'name': row.name,
'price': row.price,
}
)
csvfile = open('testdump.csv', 'a+')
for row in rows:
writer.writerow(dict(
(k, v.encode('utf-8') if type(v) is unicode else v) for k, v in row.iteritems()
))
csvfile.close()
which results in only the header being written. Any ideas?