Using Python to execute a series of SQL queries, and would like the output of each iteration of my query to be exported as its own csv file.
For example:
clients = ['Ellen','Jose','Tina']
for client in clients:
print(client)
with open('/sales.csv', 'wt') as outfile:
dw=csv.writer(outfile)
dw.writerow(['index', 'client','product','sales'])
query = """
SELECT '{}' as client,
product,
COUNT(1) AS sales
FROM datasource
GROUP BY 1, 2
ORDER BY 3 DESC
LIMIT 100""".format(market,market)
with open('sales.csv'.format(client,client), 'w') as output:
output.write(client)
I want a filename of say sales_ellen.csv, sales_jose.csv -- I know this isn't doing it (it's appending each one in the sales.csv file). thanks
Just change your open
statement to format in the name of the client:
with open('/sales_%s.csv'%client, 'wt') as outfile: