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!