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

15,015

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

Share:
15,015
Admin
Author by

Admin

Updated on August 02, 2022

Comments

  • Admin
    Admin almost 2 years

    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.