Create unique CSVs named for each iteration of my for loop

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

2 answers

  • answered 2018-11-07 20:05 Alex

    You aren't providing any place for client to be used in the call to .format().

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

    You can read about string formatting in Python here.

  • answered 2018-11-07 20:05 C.Nivs

    Just change your open statement to format in the name of the client:

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