Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write my output to a CSV in multiple columns in Python

Tags:

python

csv

excel

I can't figure out how to write my output of my program to a CSV file in columns.

Currently, I'm doing

print(var1, file=outputfile)

but it only writes to a file, not specify which column its in. I'm planning on using csv module, but I'm not too sure how to make each variable write itself to a single column in my excel file. EG:

Var1 to column A in excel.

Var2 to column B in excel ...

Appreciate any directions and advice.


1 Answers

You need to decide what columns you want to write out. As you've mentioned, you want var1 and var2 written to separate columns. You could achieve this using this:

import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ['var1', 'var2']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'var1': var1, 'var2': var2})

This will write the values of var1 and var2 to separate columns named var1 and var2

like image 52
deborah-digges Avatar answered Mar 10 '26 21:03

deborah-digges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!