简体   繁体   中英

Writing into CSV using python - Datewise columns

I have to write result of a number of metrics in a CSV file for past 14 days. First column contains name of all metrics and then other columns are 14 subsequent dates. The result of these metrics are written to the each cell corresponding to that metrics row and date column.

I did using a python code. For each date I am calculating the metrics and storing in separate variables. I am confused on how to write these into the above described CSV format. Which is the right data structure. Do I need to have separate list for every metrics or dictionaries can help?

Code is too long I am just writing the flow - Code -

  for each date:
               result_matrix_1=query(DB1)
               result_matrix_1=query(DB2)
               # Here i am confused with the DS to store these results in to CSV

sample output type -

Metric    date1    date2

session   21       34

users     10       16

first you need to create a list like this

['name1','date1'],['name2','date2'],......,['name14','date14']

or any other way like

['name1','date1','date2','date3','date4','date5'], ['name2','date1','date2','date3','date4','date5'],......,['name14','date1','date2','date3','date4','date5']

then you write this list into you .csv file using code like this:

a = [['name1','date1'],['name2','date2'],......,['name14','date14']]
import csv

with open("matrix.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM