Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Concatenate 3 lists into csv file?

Tags:

python

I have three lists:

name = ['rob', 'mike', 'bob'] age = ['19, '32', '88'] id = ['aaa', 'bbb', 'ccc']

Is there a way to concatenate these vertically and get a CSV as below?

rob, 19, aaa mike, 32, bbb bob, 88, ccc

like image 579
weebok Avatar asked Aug 09 '26 01:08

weebok


2 Answers

You can utilize csv module and zip to do this.

name = ['rob', 'mike', 'bob']
age = ['19', '32', '88']
id = ['aaa', 'bbb', 'ccc']
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)

    data = list(zip(name, age, id))
    for row in data:
        row = list(row)
        spamwriter.writerow(row)
print("Program completed")

Output:

enter image description here

like image 176
arsho Avatar answered Aug 11 '26 15:08

arsho


By using pandas

import pandas as pd 
pd.DataFrame({'name':name,'age':age,'id':id}).to_csv('your.csv')

enter image description here

like image 32
BENY Avatar answered Aug 11 '26 16:08

BENY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!