简体   繁体   中英

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.

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

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 ie 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()

Extending @CalebJ's answer, shorter version could be like this:

list_1 = ["Hello", "World", "Monty", "Python"]
list_2 = [1, 2, 3, 4]


file = open("columns.txt", "w")
writer = csv.writer(file)

for w in range(4):
iterate through integers 0-3

writer.writerow([list_1[w], list_2[w]])

file.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM