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

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.



Solution 1:[1]

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

Solution 2:[2]

create a list containing the rows, then write them line by line using csv's writerows function. This is useful if your column has a couple of entries i.e. the key has many values


import csv
list_column=["column_A","column_B"]
column_A= ["var_1"]
column_B= ["var_2"]
list_row[]

#to create a list full of rows as the writerow function reads data row-wise
for i in range(len(column_A)):
    list_temp=[column_A[i],column_B[i]]
    list_row.append(list_temp)


with open (your_csv_file_name, 'w', newline="") as entry:
    writer=csv.writer(entry)
    writer.writerow(list_column)
    writer.writerows(list_row)

    entry.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 deborah-digges
Solution 2 CalebJ