使用Python执行一系列SQL查询,并希望将查询的每次迭代输出都导出为自己的csv文件。
例如:
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)
我想要一个名为sales_ellen.csv,sales_jose.csv的文件名-我知道这并没有做到(它会将每个文件追加到sales.csv文件中)。谢谢
答案 0 :(得分:5)
答案 1 :(得分:0)
只需将您的open
语句更改为客户端名称的格式:
with open('/sales_%s.csv'%client, 'wt') as outfile: