Writing to a CSV file with only one header line

2.9k Views Asked by At

I'm currently working with several files and want to write to a csv. I open them all up in a for loop and do calculations based on information in the files. I want to write all this data to a single csv file.

I have this code within my for loop:

header = ['cost', 'tax', 'percentage_of_pay']
data = [price, taxes, pay_percentage]

with open('Sales-and-cost.csv', 'a+') as f:
    writer=csv.writer(f, delimiter='\t', lineterminator='\n')
    writer.writerow([header])
    writer.writerow([data])

Yet it puts the header information in every time it runs through the files, looking something like this:

cost tax percentage_of_pay
---- ---- -----------------
cost tax percentage_of_pay
--- --- -----------------
cost tax percentage_of_pay
--- --- -----------------

Basically, it rewrites the header line multiple times, when I only want it once in the top line.

I'm also running into problems where the data will write in, but part of it will be in one column and another part in another column. For example, the cost column will have the value and the tax column will have the units for the value in the cost column, so instead of there only being three columns with data written in, there's six. Here's an example:

cost tax percentage_of_pay
units for cost cost value units for tax

Any thoughts on how to fix these problems? Thanks!

1

There are 1 best solutions below

2
On BEST ANSWER

There are two issues with your code, the first is data is an list yet you're enclosing it in another list, i.e. [header] is the same as [['cost', 'tax', 'percentage_of_pay']] which is an list of lists.

Second you would normally write the header first then write the data in a loop one per data row

You probably want something like:

with open('Sales-and-cost.csv', 'w') as f:
    writer=csv.writer(f, delimiter='\t', lineterminator='\n')
    writer.writerow(header)
    
    for row in rows:
        writer.writerow(row)

Where rows is a list of lists containing the output data, i.e.

rows = [[price_1, taxes_1, pay_percentage_1],[price_2, taxes_2, pay_percentage_2],[price_3, taxes_3, pay_percentage_3]]