Reputation: 3
I am using the following way to create the row headers:
header_names = ["Test Number", "result", "output_value","duration_of_test"]
csvwriter = csv.DictWriter(open(out_file, 'wb'), delimiter=',', fieldnames=header_names)
csvwriter.writeheader()
In the above code, when we are creating the header, by default it creates row header. But is there any way to create column header i.e., first column is header column and rest of the columns are test results.
Upvotes: 0
Views: 109
Reputation: 46759
In order to do what you need, you will need to have all of your data ready to be written. When writing to a file, it will always be a row at a time, it is not possible to write a column at a time. As such you would need to take the following kind of approach:
import csv
out_file = 'output.csv'
header_names = ["Test Number", "result", "output_value","duration_of_test"]
data = [[1, 5, 10, 20], [2, 6, 20, 25], [3, 7, 8, 15]]
data.insert(0, header_names)
with open(out_file, 'wb') as f_output:
csv_output = csv.writer(f_output)
csv_output.writerows(zip(*data))
Where data
holds all of your test results. First the header_names
are added to the start of the data list. Then a trick using Python's zip
function has the effect of transposing your data into the format you were looking for.
This would give you the following kind of output:
Test Number,1,2,3
result,5,6,7
output_value,10,20,8
duration_of_test,20,25,15
Upvotes: 1