4

I have 2 lists let's say

a = [1,2,3] 
b = [4,5,6]

I want to write them in two columns in CSV file so when I open the excel sheet I see something like this :

col1              col2

1                  4

2                  5

3                  6

How can I do this?

I used zip(a,b) but the result is stored in one column:

col1 

1 4

2 5

3 6

3 Answers 3

3

You need to use csv.Dictwriter() to be able to specify the field names.

import csv

with open('numbers.csv', 'w', newline='') as csvfile:
    fieldnames = ['col1', 'col2']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for i, j in zip(a, b):
        writer.writerow({'col1': i, 'col2': j})

Or instead of a regular for loop you could use writerows and a list comprehension:

writer.writerows([{'col1': i, 'col2': j} for i,j in zip(a,b)])
Sign up to request clarification or add additional context in comments.

Comments

2

Using pandas is very easy. Just:

import pandas as pd

and then:

In [13]: df = pd.DataFrame({'col1':a, 'col2':b})

In [14]: df
Out[14]: 
   col1  col2
0     1     4
1     2     5
2     3     6

In [15]: df.to_csv('numbers.csv', index=False)

Basically you are building a dataframe with your lists and then save back to .csv. Hope that helps.

Comments

0

I found this solution, where you dont need an extra loop:

fieldnames = ["x_value", "y_value"]

def createcsv(fieldnames, file):
# csv for Data generation
with open(file, 'w') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    csv_writer.writeheader()

def writedata(x, y, fieldnames, file):
with open(file, 'a') as csv_file:
    csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
    info = {
        "x_value": x,
        "y_value": y
    }
    csv_writer.writerow(info)

Of course you could put those into one function, but this solution is created so that you can save your values during runtime, for example in a loop and dont have to create the fileheaders everytime again.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.