创建以 for 循环的每次迭代命名的唯一 CSV

Create unique CSVs named for each iteration of my for loop

使用 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 文件中)。谢谢

您没有为 client 提供任何位置,以便在对 .format() 的调用中使用。

fname = 'sales_{}.csv'.format(client)
with open(fname, 'w') as output:
    ...

您可以在 Python here 中阅读有关字符串格式的内容。

只需将您的 open 语句更改为客户名称格式:

with open('/sales_%s.csv'%client, 'wt') as outfile: