【问题标题】:Create unique CSVs named for each iteration of my for loop为我的 for 循环的每次迭代创建唯一的 CSV
【发布时间】:2018-11-07 20:02:20
【问题描述】:

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

【问题讨论】:

    标签: python file for-loop string-formatting


    【解决方案1】:

    您没有为client 提供任何用于调用.format() 的位置。

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

    您可以阅读 Python here 中的字符串格式化。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2019-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-13
        • 2020-08-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多