3

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
  • how columns should be called ? Commented Jan 10, 2016 at 8:38

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. Straight to the point and got me going. Do you know any place to learn more about the CSV module? The docs are quite challenging for me.
There's a wonderful resource Pymotw(Python module of the week) that explains the usage of a lot of modules. Here's the one for the CSV module: pymotw.com/2/csv.
0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.